簡體   English   中英

正則表達式在java中查找字符串中的特定單詞

[英]Regex to find a specific word in a string in java

我需要一些正則表達式的幫助:我試圖檢查一個句子是否包含一個特定的單詞。

讓我們以此主題的標題為例:

“正則表達式在字符串中查找特定單詞”

我需要找到它是否包含單詞if ,在這種情況下它是假的。

我不能使用方法contains,因為在這種情況下它會返回true(spec * if * ic)

我正在考慮使用方法匹配,但我有點正規表達式的菜鳥。

基本上,匹配方法的輸入中的正則表達式需要指定正在查找的單詞之前和單詞之后的字符不是字母(因此它不能包含在該單詞中)或單詞是在句子的開頭或結尾

非常感謝!

使用以下正則表達式:

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

\\b匹配單詞邊界。

熟悉正則表達式可以解決您的任務

在你的情況下

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

一個簡短的解釋:

匹配任何角色,

*? 是零次或多次,

\\ b是單詞邊界。

正則表達式的一個很好的解釋可以在這里找到

使用它來匹配字符串中的特定單詞:

   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