(change: a positive lookbehind is not needed, only a match is performed, not a replacement)
You are another victim of unnamed Java regular expression matching methods.
.matches() rather, unfortunately, trying to match the entire input, which is a clear violation of the definition of "matching regular expressions" (a regular expression can match anywhere in the input). The method you need to use is .find() .
This is the Braindead API, and unfortunately Java is not the only language that has such erroneous method names. Python also pleads guilty.
Also, you have a problem that \\b will detect at word boundaries, and # not part of the word. You need to use alternation that defines either the beginning of the input or a space.
Your code should look like this (not fully qualified classes):
Pattern p = Pattern.compile("(^|\\s)#SP\\b", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher("s #SP s"); if (m.find()) { System.out.println("Match!"); }
source share