简体   繁体   中英

Regex to find a specific word in a string in java

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM