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!
Use the following regular expression:
".*\\bif\\b.*"
\b
match word boundary.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With