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:
\"Re
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
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
Use the following regular expression:
".*\\bif\\b.*"
\b
match word boundary.