Java正则表达式仅第一次匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18838906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java regex first match only
提问by Mark Kennedy
How do I tell the following regex to only find the FIRST match? The following code keeps finding all possible regex within the string.
我如何告诉以下正则表达式只找到第一个匹配项?以下代码不断在字符串中查找所有可能的正则表达式。
i.e. I'm looking only for the indices of the substring (200-800;50]
即我只在寻找子字符串的索引 (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!");
}
}
采纳答案by ATG
matcher.group(1)
will return the first match.
matcher.group(1)
将返回第一场比赛。
If you mean lazy matching instead of eager matching, try adding a ? after the + in the regular expression.
如果您的意思是懒惰匹配而不是急切匹配,请尝试添加 ? 在正则表达式中的 + 之后。
Alternatively, you can consider using something more specific than .+
to match the content between the brackets. If you're only expecting letters, numbers and a few characters then maybe something like [-A-Z0-9;_.]+
would work better?
或者,您可以考虑使用更具体.+
的内容,而不是匹配括号之间的内容。如果你只需要字母、数字和几个字符,那么也许类似的东西[-A-Z0-9;_.]+
会更好?