Dejan Dejan - 2 months ago 16
Java Question

Java Matcher Pattern issue

I am trying to extract everything that is after this string path

/share/attachments/docs/
. All my strings are starting with
/share/attachments/docs/


For example:
/share/attachments/docs/image2.png

Number of characters after ../docs/ is not static!

I tried with

Pattern p = Pattern.compile("^(.*)/share/attachments/docs/(\\d+)$");
Matcher m = p.matcher("/share/attachments/docs/image2.png");
m.find();
String link = m.group(2);
System.out.println("Link #: "+link);


But I am getting Exception that:
No match found.

Strange because if I use this:

Pattern p = Pattern.compile("^(.*)ABC Results for draw no (\\d+)$");
Matcher m = p.matcher("ABC Results for draw no 2888");


then it works!!!

Also one thing is that in some very rare cases my string does not start with
/share/attachments/docs/
and then I should not parse anything but that is not related directly to the issue, but it will be good to handle.

Answer

I am getting Exception that: No match found.

This is because image2.png doesn't match with \d+ use a more appropriate pattern like .+ assuming that you want to extract image2.png.

Your regular expression will then be ^(.*)/share/attachments/docs/(.+)$


In case of ABC Results for draw no 2888, the regexp ^(.*)ABC Results for draw no (\\d+)$ works because you have several successive digits at the end of your String while in the first case you had image2.png that is a mix of letters and digits which is the reason why there were no match found.


Generally speaking to avoid getting an IllegalStateException: No match found, you need first to check the result of find(), if it returns true the input String matches:

if (m.find()) {
   // The String matches with the pattern
   String link = m.group(2);    
   System.out.println("Draw #: "+link);
}  else {
   System.out.println("Input value doesn't match with the pattern");
}