Regex to find a specific word in a string in java

后端 未结 3 1216
栀梦
栀梦 2020-12-10 21:35

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

相关标签:
3条回答
  • 2020-12-10 22:19

    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

    0 讨论(0)
  • 2020-12-10 22:20

    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
    

    0 讨论(0)
  • 2020-12-10 22:35

    Use the following regular expression:

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

    \b match word boundary.

    0 讨论(0)
提交回复
热议问题