Java regular expression to match parameters within a function - java

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

Related

How to extract parameter and values from a string using regex

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.

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
...
}

First and second tocen regex

How could I get the first and the second text in "" from the string?
I could do it with indexOf but this is really boring ((
For example I have a String for parse like: "aaa":"bbbbb"perhapsSomeOtherText
And I d like to get aaa and bbbbb with the help of Regex pattern - this will help me to use it in switch statement and will greatly simplify my app/
If all that you have is colon delimited string just split it:
String str = ...; // colon delimited
String[] parts = str.split(":");
Note, that split() receives regex and compilies it every time. To improve performance of your code you can use Pattern as following:
private static Pattern pColonSplitter = Pattern.compile(":");
// now somewhere in your code:
String[] parts = pColonSplitter.split(str);
If however you want to use pattern for matching and extraction of string fragments in more complicated cases, do it like following:
Pattert p = Patter.compile("(\\w+):(\\w+):");
Matcher m = p.matcher(str);
if (m.find()) {
String a = m.group(1);
String b = m.group(2);
}
Pay attention on brackets that define captured group.
Something like this?
Pattern pattern = Pattern.compile("\"([^\"]*)\"");
Matcher matcher = pattern.matcher("\"aaa\":\"bbbbb\"perhapsSomeOtherText");
while (matcher.find()) {
System.out.println(matcher.group(1));
}
Output
aaa
bbbbb
String str = "\"aaa\":\"bbbbb\"perhapsSomeOtherText";
Pattern p = Pattern.compile("\"\\w+\""); // word between ""
Matcher m = p.matcher(str);
while(m.find()){
System.out.println(m.group().replace("\"", ""));
}
output:
aaa
bbbbb
there are several ways to do this
Use StringTokenizer or Scanner with UseDelimiter method

Regex for matching pattern within quotes

I have some input data such as
some string with 'hello' inside 'and inside'
How can I write a regex so that the quoted text (no matter how many times it is repeated) is returned (all of the occurrences).
I have a code that returns a single quotes, but I want to make it so that it returns multiple occurances:
String mydata = "some string with 'hello' inside 'and inside'";
Pattern pattern = Pattern.compile("'(.*?)+'");
Matcher matcher = pattern.matcher(mydata);
while (matcher.find())
{
System.out.println(matcher.group());
}
Find all occurences for me:
String mydata = "some '' string with 'hello' inside 'and inside'";
Pattern pattern = Pattern.compile("'[^']*'");
Matcher matcher = pattern.matcher(mydata);
while(matcher.find())
{
System.out.println(matcher.group());
}
Output:
''
'hello'
'and inside'
Pattern desciption:
' // start quoting text
[^'] // all characters not single quote
* // 0 or infinite count of not quote characters
' // end quote
I believe this should fit your requirements:
\'\w+\'
\'.*?' is the regex you are looking for.

Categories

Resources