Been trying different expressions to fetch string inside single quotation marks. As of now I was using a simple regex : '(.*?)'
But this one fails on particular scenario when there are nested quotation marks in string.
Example 1: A = "someMethod('abc','de'f','ghi')" Matching Group 1 : abc Group 2 : de'f Group 3 : ghi
Any help is much appreciated.
Not very expert in creating regular expressions but tried a few solutions currently present on StackOverflow. Didn't work as I expected.
CodePudding user response:
.*?
is called Reluctant Quantifiers it try eat the char of your string one by one till it find a match but if you used .* it's greedy match which will eat your whole string then drop one by one till it find match
so your regex be : '(.*)'
or
you can use the boundry option for your regex
so it be like '(.*?)'$
check this one for extra explanation https://dev.java/learn/regex/quantifiers/#greedy-reluctant-possessive
and of course you can check the whole tutorial https://dev.java/learn/regex/
and you can try your regex here https://regex101.com/ make sure to choose the java flavor
hope that help and have a nice day :)
CodePudding user response:
If your single quoted substrings are always separated by ,
or are enclosed by parenthesis, you can lookahead for these two characters in the regex, '.*?'(?=[,\)])
.
Demo:
class Main {
public static void main(String[] args) {
String str = "someMethod('abc','de'f','ghi')";
Matcher matcher = Pattern.compile("'.*?'(?=[,\\)])").matcher(str);
while (matcher.find())
System.out.println(matcher.group());
}
}
Output:
'abc'
'de'f'
'ghi'