Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to find a specific word in a string in java

Tags:

java

regex

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!

like image 922
Epi Avatar asked Nov 27 '22 21:11

Epi


2 Answers

Use the following regular expression:

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

\b match word boundary.

like image 196
falsetru Avatar answered Dec 05 '22 16:12

falsetru


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

like image 22
Bharat Avatar answered Dec 05 '22 18:12

Bharat