Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find second occurrence of pattern in regex

Tags:

java

regex

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'

like image 841
TNN Avatar asked Dec 17 '25 11:12

TNN


1 Answers

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

like image 197
Wiktor Stribiżew Avatar answered Dec 20 '25 04:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!