如何告诉以下正则表达式仅查找第一个匹配项?以下代码不断查找字符串中所有可能的正则表达式。
即我只寻找子字符串的索引(200-800;50]
public static void main(String[] args) {
String regex = "(\\[|\\().+(\\]|\\))";
String testName= "DCGRD_(200-800;50]MHZ_(PRE|PST)_(TESTMODE|REG_3FD)";
Pattern pattern =
Pattern.compile(regex);
Matcher matcher =
pattern.matcher(testName);
boolean found = false;
while (matcher.find()) {
System.out.format("I found the text" +
" \"%s\" starting at " +
"index %d and ending at index %d.%n",
matcher.group(),
matcher.start(),
matcher.end());
found = true;
}
if (!found){
System.out.println("Sorry, no match!");
}
}
matcher.group(1)
将返回第一个匹配项。
如果您指的是惰性匹配而不是急切匹配,请尝试添加 ?在正则表达式中的 + 之后。
或者,您可以考虑使用比.+
来匹配括号内的内容。如果您只需要字母、数字和一些字符,那么可能是这样的[-A-Z0-9;_.]+
效果会更好吗?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)