How to extract parameter and values from a string using regex - java

I need to extract a param and the value for that param from a string ((created_date{[1976-03-06T23:59:59.999Z TO *]}|1)). Here param is created_date. Value is 1976-03-06T23:59:59.999Z TO * where * denotes no restriction. I need to extract the data as shown below i,e it should be an array of string.
created_date
1976-03-06T23:59:59.999Z
*
1
I have tried some online regex tool to find a suitable regex and also tried some code on trial and error basis.
String str = "((created_date{[1976-03-06T23:59:59.999Z TO *]}|1))";
String patt = "\\((.*)\\{(.*)\\}\\|(1|0)\\)";
Pattern p = Pattern.compile(patt);
Matcher m = p.matcher(str);
MatchResult result = m.toMatchResult();
System.out.println(result.group(1));
similary result.group(2) and 3.. depending on the result.groupCount().
I need to extract the data as shown below i,e it should be an array of string.
created_date
1976-03-06T23:59:59.999Z
*
1

You can use the following :
String str = "((created_date{[1976-03-06T23:59:59.999Z TO *]}|1))";
String patt = "\\(\\(([^{]+)\\{\\[([^ ]+) TO ([^]]+)]}\\|([01])\\)\\)";
Pattern p = Pattern.compile(patt);
Matcher m = p.matcher(str);
if (m.matches()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
System.out.println(m.group(3));
System.out.println(m.group(4));
}
Try it here !
Note that you need to invoke a Matcher's find(), matches() or more rarely lookingAt() before you can use most of its other methods, including the toMatchResult() you were trying to use.

Related

JAVA Get text from String

Hi I get this String from server :
id_not="autoincrement"; id_obj="-"; id_tr="-"; id_pgo="-"; typ_not=""; tresc="Nie wystawił"; datetime="-"; lon="-"; lat="-";
I need to create a new String e.x String word and send a value which I get from String tresc="Nie wystawił"
Like #Jan suggest in comment you can use regex for example :
String str = "id_not=\"autoincrement\"; id_obj=\"-\"; id_tr=\"-\"; id_pgo=\"-\"; typ_not=\"\"; tresc=\"Nie wystawił\"; datetime=\"-\"; lon=\"-\"; lat=\"-\";";
Pattern p = Pattern.compile("tresc(.*?);");
Matcher m = p.matcher(str);
if (m.find()) {
System.out.println(m.group());
}
Output
tresc="Nie wystawił";
If you want to get only the value of tresc you can use :
Pattern p = Pattern.compile("tresc=\"(.*?)\";");
Matcher m = p.matcher(str);
if (m.find()) {
System.out.println(m.group(1));
}
Output
Nie wystawił
Something along the lines of
Pattern p = Pattern.compile("tresc=\"([^\"]+)\");
Matcher m = p.matcher(stringFromServer);
if(m.find()) {
String whatYouWereLookingfor = m.group(1);
}
should to the trick. JSON parsing might be much better in the long run if you need additional values
Your question is unclear but i think you get a string from server and from that string you want the string/value for tresc. You can first search for tresc in the string you get. like:
serverString.substring(serverString.indexOf("tresc") + x , serverString.length());
Here replace x with 'how much further you want to pick characters.
Read on substring and delimiters
As values are separated by semicolon so annother solution could be:
int delimiter = serverstring.indexOf(";");
//in string thus giving you the index of where it is in the string
// Now delimiter can be -1, if lets say the string had no ";" at all in it i.e. no ";" is not found.
//check and account for it.
if (delimiter != -1)
String subString= serverstring.substring(5 , iend);
Here 5 means tresc is on number five in string, so it will five you tresc part.
You can then use it anyway you want.

Java regular expression to match parameters within a function

I would like to write a regular expression to extract parameter1 and parameter2 of func1(parameter1, parameter2), the length of parameter1 and parameter2 ranges from 1 to 64.
(func1) (\() (.{1,64}) (,\\s*) (.{1,64}) (\))
My version can not deal with the following case (nested function)
func2(func1(ef5b, 7dbdd))
I always get a "7dbdd)" for parameter2. How could I solve this?
Use "anything but closing parenthesis" ([^)]) instead of simply "anything" (.):
(func1) (\() (.{1,64}) (,\s*) ([^)]{1,64}) (\))
Demo: https://regex101.com/r/sP6eS1/1
Use [^)]{1,64} (match all except )) instead of .{1,64} (match any) to stop right before the first )
(func1) (\() (.{1,64}) (,\\s*) (.{1,64}) (\))
^
replace . with [^)]
Example:
// remove whitespace and escape backslash!
String regex = "(func1)(\\()(.{1,64})(,\\s*)([^)]{1,64})(\\))";
String input = "func2(func1(ef5b, 7dbdd))";
Pattern p = Pattern.compile(regex); // java.util.regex.Pattern
Matcher m = p.matcher(input); // java.util.regex.Matcher
if(m.find()) { // use while loop for multiple occurrences
String param1 = m.group(3);
String param2 = m.group(5);
// process the result...
}
If you want to ignore whitespace tokens, use this one:
func1\s*\(\s*([^\s]{1,64})\s*,\s*([^\s\)]{1,64})\s*\)"
Example:
// escape backslash!
String regex = "func1\\s*\\(\\s*([^\\s]{1,64})\\s*,\\s*([^\\s\\)]{1,64})\\s*\\)";
String input = "func2(func1 ( ef5b, 7dbdd ))";
Pattern p = Pattern.compile(regex); // java.util.regex.Pattern
Matcher m = p.matcher(input); // java.util.regex.Matcher
if(m.find()) { // use while loop for multiple occurrences
String param1 = m.group(1);
String param2 = m.group(2);
// process the result...
}
Hope this helpful
func1[^\(]*\(\s*([^,]{1,64}),\s*([^\)]{1,64})\s*\)
(func1) (\() (.{1,64}) (,\\s*) ([^)]{1,64}) (\))
^.*(func1)(\()(.{1,64})(,\s*)(.{1,64}[A-Za-z\d])(\))+
Working example: here

Matcher not finding matches

I'm trying to extract the numbers in the following string:
09/29/2014
I am currently using the code:
Pattern p = Pattern.compile("([0-9]{2})/([0-9]{2})/([0-9]{4})");
Matcher m = p.matcher(startDatepicker);
String startYear = m.group(3);
String startMonth = m.group(1);
String startDay = m.group(2);
startDatepicker contains: 09/29/2014
However, I am not receiving any matches.. I also tried escaping the forward slashes with \\ but that also didn't work.
Am I missing something?
Thanks for your help.
Before you could access the matched groups, you need to call find() on the matcher, and check that it has found a match:
Pattern p = Pattern.compile("([0-9]{2})/([0-9]{2})/([0-9]{4})");
Matcher m = p.matcher(startDatepicker);
if (!m.find()) {
return;
}
String startYear = m.group(3);
String startMonth = m.group(1);
String startDay = m.group(2);
The call of m.find() positions the matcher on the first match.
Demo.
You need to call find() to iterate through your match groups.
Pattern p = Pattern.compile("([0-9]{2})/([0-9]{2})/([0-9]{4})");
Matcher m = p.matcher(startDatepicker);
while (m.find()) {
...
}
The find() method searches for occurrences of the regex in the input passed to p.matcher(). If multiple matches can be found, this method will find the first, and then move to the next match for each subsequent call.

Pattern Matching with dynamic matcher

Sample input string : Customer ${/xml:Name} has Ordered Product ${/xml:product} of ${/xml:unit} units.
i able to find get strings that match ${ ...... } using "\\$\\{.*?\\}"
I resolve the value for string from xml and now i have to replace the value back in input string.
i am using this method,
Pattern MY_PATTERN = Pattern.compile("\\$\\{.*?\\}");
Matcher m = MY_PATTERN.matcher(inputstring);
while (m.find()) {
String s = m.group(0); // s is ${/xml:Name}
// escaping wild characters
s = s.replaceAll("${", "\\$\\{"); // s is \$\{/xml:Name}
s = s.replaceAll("}", "\\}"); // s is \$\{/xml:Name\}
Pattern inner_pattern = Pattern.compile(s);
Matcher m1 = inner_pattern.matcher(inputstring);
name = m1.replaceAll(xPathValues.get(s));
}
but i get error at s = s.replaceAll("${", "\\$\\{"); i get Pattern Syntax Exception
You must escape the { too, try $\\{
Instead of:
s = s.replaceAll("${", "\\$\\{"); // s is \$\{/xml:Name}
s = s.replaceAll("}", "\\}"); // s is \$\{/xml:Name\}
You can use it without regex method String#replace(string):
s = s.replace("${", "\\$\\{").replace("}", "\\}"); // s is \$\{/xml:Name\}
It's because you could have a regexp likea{1,4} means to match a,aa,aaa,aaaa so a times 1 to 4, java tries to interpret your regexp like this, therefore try escaping the {
Yes, you must escape the {, but I would rather capture what's inside the braces:
Pattern MY_PATTERN = Pattern.compile("\\$\\{/xml:(.*?)\\}");
Matcher m = MY_PATTERN.matcher(inputstring);
while (m.find()) {
name = m.group(1); // s is Name
...
}

regex: Java: match word between 2 spaces

How can I extract the "id" from the following string using regex.
string = 11,"col=""book"" id=""title"" length=""10""
I need to be able to extract the "id" header along with the value "title".
outcome: id=""title""
I am trying to the use split function with a regex to extract the identifier from the string.
Try this:
String result = "col=\"book\" id=\"title\" length=\"10\"";
String pattern = ".*(id\\s*=\\s*\"[^\"]*\").*";
System.out.println(result.replaceAll(pattern,"$1"));
Cheers!
Use Pattern and Matcher classes to find what you are looking for. Try to find these regex \\bid=[^ ]*.
String data = "string = 11,\"col=\"\"book\"\" id=\"\"title\"\" length=\"\"10\"\"";
Matcher m = Pattern.compile("\\bid=[^ ]*").matcher(data);
if (m.find())
System.out.println(m.group());

Categories

Resources