在正则表达式中查找第二次出现的模式 [英] Find second occurrence of pattern in regex
本文介绍了在正则表达式中查找第二次出现的模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的输入是
String t1 = "test1:testVar('varName', 'ns2:test')";
String t2 = "test2:testVar('varName', 'ns2:test', 'defValue')";
String patternString = "\('.*',\s*('.*:.*').*\)";
我尝试仅捕获第二对 ' ' 之间的文本,即: ns2:test我的模式是: ('.',\s('.:.').*) 并且对于第一个字符串它是可以的,但是对于第二个我得到了结果: 'ns2:test', 'defValue'
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*('.*?:.*?').*?\)
^^^ ^^^ ^^^ ^^^
查看正则表达式演示.
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 ,
.
这篇关于在正则表达式中查找第二次出现的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文