4

I need some help with regular expressions: I'm trying to check if a sentence contains a specific word.

let's take for example the title of this topic:

"Regex to find a specific word in a string"

I need to find if it contains the word if, which in this case it's false.

I can't use the method contains because it would return true in this case (spec*if*ic)

I was thinking about using the method matches but I'm kinda noob with regular expressions.

Basically the regex in input to the matched method needs to specify that the character right before the word I'm looking for and right after the word is not alphabetic (so it couldn't be contained in that word) or that the word is at the beginning or at the end of the sentence

thanks a lot!

3 Answers 3

18

Use the following regular expression:

".*\\bif\\b.*"

\b match word boundary.

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

2 Comments

uhm this doesn't work. it always returns false (I already tried it before posting it, maybe I'm doing something wrong) System.out.println("Regex to find if a specific word in a string in java".matches("\\bif\\b")); for example returns false and it should return true
System.out.println("Regex to find if a specific word in a string in java".matches("\\bif\\b"));
8

A good knowledge of Regular Expression can solve your task

In your case

String str = "Regex to find a specific word in a string in java"
        str.matches(".*?\\bif\\b.*?");  \\ return false
String str1 = "print a word if you found"
        str1.matches(".*?\\bif\\b.*?");  \\ return true

A short explanation:

. matches any character,

*? is for zero or more times,

\b is a word boundary.

A good Explanation of Regular expression can be found Here

Comments

2

Use this to match specific words in a string:

   String str="Regex to find a specific word in a string";
   System.out.println(str.matches(".*\\bif\\b.*"));   //false 
   System.out.println(str.matches(".*\\bto\\b.*"));   //true

1 Comment

@Epi Do you want the index Returned ? Am not able to understand your last para...

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.