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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18289929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:06:42  来源:igfitidea点击:

Regex to find a specific word in a string in java

javaregex

提问by Epi

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!

多谢!

采纳答案by falsetru

Use the following regular expression:

使用以下正则表达式:

".*\bif\b.*"

\bmatch word boundary.

\b匹配词边界。

回答by boxed__l

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


回答by Bharat

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

可以在这里找到正则表达式的一个很好的解释