简体   繁体   English

Java RegEx找不到匹配错误

[英]Java RegEx no match found error

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. 任何帮助,将不胜感激。

No match has been attempted. 尚未尝试匹配。 Call find() before calling group() . 在调用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

The Matcher#group(int) throws : Matcher#group(int)抛出:

IllegalStateException - If no match has yet been attempted, or if the 
previous match operation failed.

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. 您的测试字符串与“ upload”之后的斜杠匹配,因为\\w不匹配斜杠, \\w仅包含单词字符。 Word characters are letters, digits, and underscores. 文字字符是字母,数字和下划线。 See: http://www.regular-expressions.info/charclass.html#shorthand 请参阅: http : //www.regular-expressions.info/charclass.html#shorthand

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM