my inputs is
String t1 = "test1:testVar('varName', 'ns2:test')";
String t2 = "test2:testVar('varName', 'ns2:test', 'defValue')";
String patternString = "\('.*',\s*('.*:.*').*\)";
I try to capture only text between second pair of ' ', ie: ns2:test my pattern is : ('.',\s('.:.').*) and for first string it is ok,but for second i got as result: 'ns2:test', 'defValue'
You need to make all parts of your pattern lazy:
\('.*?',\s*('.*?:.*?').*?\)
^^^ ^^^ ^^^ ^^^
See the regex demo.
Java demo:
String t1 = "test1:testVar('varName', 'ns2:test')";
String t2 = "test2:testVar('varName', 'ns2:test', 'defValue')";
String patternString = "\\('.*?',\\s*('.*?:.*?').*?\\)";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(t1);
while (matcher.find()){
System.out.println(matcher.group(1));
}
matcher = pattern.matcher(t2);
while (matcher.find()){
System.out.println(matcher.group(1));
}
An alternative is to use negated character classes, but it may cause issues if your input is more complex than what you posted:
\('[^',]*',\s*('[^',]*:[^',]*')
See a regex demo, where [^',] matches any character but a ' and ,.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With