Java RegEx error without errors

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

 String requestpattern = "^[A-Za-z]+ \\/+(\\w+)"; Pattern p = Pattern.compile(requestpattern); Matcher matcher = p.matcher(requeststring); return matcher.group(1); 

where is the query string

 POST //upload/sendData.htm HTTP/1.1 

Any help would be appreciated.

+6
source share
3 answers

The match was not completed. 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 
+24
source

Match group # (int) throws:

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

Your expression requires one or more letters, followed by a space, followed by one or more slashes, and then one or more words. Your test string does not match. An exception is thrown because you are trying to access a group on a match that does not return matches.

Your test string matches the slash after "loading" because the slash does not match \w , which includes only the characters of the word. Symbols of a word are letters, numbers and underscores. See: http://www.regular-expressions.info/charclass.html#shorthand

0
source

Source: https://habr.com/ru/post/944144/


All Articles