Java RegEx 找不到匹配项错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16344088/
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 no match found error
提问by Ananda
Following regex giving me java.lang.IllegalStateException: No match found
error
以下正则表达式给我java.lang.IllegalStateException: No match found
错误
String requestpattern = "^[A-Za-z]+ \/+(\w+)";
Pattern p = Pattern.compile(requestpattern);
Matcher matcher = p.matcher(requeststring);
return matcher.group(1);
where request string is
请求字符串在哪里
POST //upload/sendData.htm HTTP/1.1
Any help would be appreciated.
任何帮助,将不胜感激。
回答by acdcjunior
No match has been attempted. Call find()
before calling group()
.
没有尝试匹配。打电话find()
之前先打电话group()
。
public static void main(String[] args) {
String requeststring = "POST //upload/sendData.htm HTTP/1.1";
String requestpattern = "^[A-Za-z]+ \/+(\w+)";
Pattern p = Pattern.compile(requestpattern);
Matcher matcher = p.matcher(requeststring);
System.out.println(matcher.find());
System.out.println(matcher.group(1));
}
Output:
输出:
true
upload
回答by NINCOMPOOP
The Matcher#group(int)throws :
该匹配器#组(INT)抛出:
IllegalStateException - If no match has yet been attempted, or if the
previous match operation failed.
回答by Adrian
Your expression requires one or more letters, followed by a space, followed by one or more forward slashes, followed by one or more word characters. Your test string doesn't match. The exception is triggered because you're trying to access a group on a matcher that returns no matches.
您的表达式需要一个或多个字母,后跟一个空格,后跟一个或多个正斜杠,后跟一个或多个单词字符。您的测试字符串不匹配。触发异常是因为您尝试访问匹配器上没有返回匹配项的组。
Your test string matches up to the slash after "upload", because the slash isn't matched by \w
, which only includes word characters. Word characters are letters, digits, and underscores. See: http://www.regular-expressions.info/charclass.html#shorthand
您的测试字符串与“上传”后的斜杠匹配,因为斜杠不匹配\w
,它只包含单词字符。单词字符是字母、数字和下划线。请参阅:http: //www.regular-expressions.info/charclass.html#shorthand