【发布时间】:2013-09-16 23:19:12
【问题描述】:
如何告诉下面的正则表达式只找到第一个匹配项?以下代码不断在字符串中查找所有可能的正则表达式。
即我只寻找子字符串 (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!");
}
}
【问题讨论】:
-
第一个匹配项将是循环的第一次迭代。只需处理一次迭代即可。或者根本没有循环,如果 find 返回 true 则简单地处理匹配。
-
这就是我要找的。谢谢
-
你的正则表达式匹配
(200-800;50]MHZ_(PRE|PST)_(TESTMODE|REG_3FD)。您需要正则表达式方面的帮助吗? -
我只需要第一次出现。即
(200-800;50]。搞定了一切! :)