0

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?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

6 Comments

of course i assume that you dont want to use string contains or indexOf/lastIndexOf
System.out.println ("int halfOfFour() { return half(4); }".matches(".*\\bhalf\\b.*")); --> true
"testfunc passing() { int halfOfFour = half(4); assert(halfOfFour == 2, "The laws of physics is on break"); }".matches(".*\\b" + Pattern.quote("half") + "\\b.*"); Still results in false...
then you need to use the pattern/matcher separately to find submatches.
try ".*\\W+"+pattern.quote(item.name)+"\\W+.*" or something.
|
1

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*

5 Comments

No, he wants to check if a full word is in the string. Canon contains non, but it is not a word. CaNon contains the word non.
In his example (half/halfOfHour) he says it should return true despite 'half' not being a full word. So I think you misread that.
Yes, but I think he is really looking for a way to check words. The capital characters mark the beginning of a word.
Actually, i want it to return true because the string includes "half(4)"... "halfOfFour" should still return false.
Like this? boolean matches = nap.code.matches("\\W*" + Pattern.quote(item.name) + "\\W*"); Cause that still does not work...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.