Having a slight regex problem. I wrote to following code to check if a word is contained within a String.
boolean matches = Pattern.matches("\\b" + Pattern.quote(item.name) + "\\b", nap.code);
item.name will be something like "half" nap.code will be something like "int halfOfFour() { return half(4); }"
Yet, my pattern match returns false... What am I doing wrong here?
Also... Is there anyway to make this return false if the word is contained within a string?
I think the pattern match will match the whole string not just a part of it. so prefix with .* and postfix with .* or something.
use pattern and matches separately and then use "find()" in matcher to find submatches
Wouldn't the Java.lang.String.contains()
method do what you want?
boolean contains = nap.code.contains(item.name);
EDIT : To return true only if the word is present, using the \\W pattern (non-word character) should help you :
\W*(YOUR_WORD)\W*
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.