在正则表达式中查找模式的第二次出现

2024-01-18

我的输入是

  String t1 = "test1:testVar('varName', 'ns2:test')";
  String t2 = "test2:testVar('varName', 'ns2:test', 'defValue')";
  String patternString = "\('.*',\s*('.*:.*').*\)";

我尝试仅捕获第二对 ' ' 之间的文本,即: ns2:test 我的模式是:('.',\s('.:.').*) 对于第一个字符串,这是可以的,但对于第二个字符串,我得到的结果是: 'ns2:test', 'defValue'


您需要使模式的所有部分变得懒惰:

\('.*?',\s*('.*?:.*?').*?\)
   ^^^       ^^^ ^^^  ^^^

See the 正则表达式演示 https://regex101.com/r/yO1eT8/3.

Java演示 http://ideone.com/SOzzlx:

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)); 
} 

另一种方法是使用否定字符类,但如果您的输入比您发布的内容更复杂,则可能会导致问题:

\('[^',]*',\s*('[^',]*:[^',]*')

See a 正则表达式演示 https://regex101.com/r/yO1eT8/2, where [^',]匹配除 a 之外的任何字符' and ,.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在正则表达式中查找模式的第二次出现 的相关文章

随机推荐