简体   繁体   English

正则表达式在java中查找字符串中的特定单词

[英]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. 我需要找到它是否包含单词if ,在这种情况下它是假的。

I can't use the method contains because it would return true in this case (spec* if *ic) 我不能使用方法contains,因为在这种情况下它会返回true(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. \\b匹配单词边界。

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. \\ b是单词边界。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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