RegEx with quotes not matching anything in Java
I may have one of the following lines:
Apple $Banana Kiwi
Apple $Banana, Kiwi
Apple $Banana. Kiwi
I need to find litterally "$ Banana"
In java 6 I used this:
String quotedStringToFind=Pattern.quote(stringTofind);
I also need to find the complete word, so I tried with this:
Pattern.compile("\\b"+quotedStringToFind+"\\b");
Nothing matches. RegEx is syntactically correct. I don't understand why this doesn't work.
+3
source to share
2 answers
[...] It matches a position called a "word boundary". This match is zero.
There are three different positions as word boundaries:
- Before the first character in the string if the first character is a word character.
- After the last character in the string, if the last character is a word character.
- Between two characters in a string, where one is a word character and the other is not a word character.
Considering
Apple $Banana Kiwi
the first scenario fails because $
it is not a word character. Thus, there can be no match before the first character in the string.
You can use spaces to delimit $Banana
.
Pattern pattern = Pattern.compile("\\s" + quotedStringToFind + "\\s");
-3
source to share
Several problems:
-
$
is a reserved character meaning "end of line". You will need to hide any reserved character (\^$.|?*+()[{
) first or compile the expression withPattern.LITERAL
as in @ Reiumeus answer. - There
$
isApple $Banana
no word boundary between space and in , since both are symbols other than a word. Assuming you want the space before or afterstringTofind
, you can use the following expression:(?<=\\s|^)\\$Banana(?=\\s|$)
(note that this won't work withPattern.LITERAL
, as it wouldn't cause distortion evasion).
+1
source to share