Java RegEx no match found error

后端 未结 3 1812
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-10 04:35

Following regex giving me java.lang.IllegalStateException: No match found error

String requestpattern = \"^[A-Za-z]+ \\\\/+(\\\\w+)\";
Pattern p         


        
相关标签:
3条回答
  • 2020-12-10 04:45

    The Matcher#group(int) throws :

    IllegalStateException - If no match has yet been attempted, or if the 
    previous match operation failed.
    
    0 讨论(0)
  • 2020-12-10 04:53

    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

    0 讨论(0)
  • 2020-12-10 04:56

    No match has been attempted. Call find() before calling 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
    
    0 讨论(0)
提交回复
热议问题