我正在嘗試撰寫一個正則運算式來匹配包含某個帶有句點的單詞的字串,例如(apple.或grape.)。我讓它在沒有句點的情況下作業,但不太確定當單詞中有句點時如何讓它作業。
我嘗試了什么:
(?i)\b(Apple|Grape)\b (Working correctly without the period)
(?i)\b(Apple\.|Grape\.)\b (Returns no matches)
應該作業的示例字串:
1 apple.
1 Apple.
apple. 2
grape. 1
test grape.
grape. test
this is a Apple. test
不應該作業的示例字串:
1apple.
1Apple.
apple.2
grape.1
testgrape.
grape.test
longwordApple.test
this is a Apple.test
uj5u.com熱心網友回復:
您可以將模式撰寫為:
\b(Apple|Grape)\.(?!\S)
解釋
\b用于防止左側部分單詞匹配的單詞邊界(Apple|Grape)捕獲蘋果或葡萄\.匹配一個點(?!\S)在右側斷言空白邊界
正則運算式演示
在帶有雙轉義反斜杠的 Java 中:
String regex = "(?<!\\S)(Apple|Grape)\\.(?!\\S)";
uj5u.com熱心網友回復:
你確定你需要正則運算式嗎?我的意思是我可以在以下幾行中想到一個普通的標記化決議器:
String s = "";
foreach(String token : s.split(" ")) { // I suggest saving the split (apparently, javac does not do a good job at caching like the C/C compiler)
if(token.equals("apple.") || token.equals("grapes.")) { // or take in a word array with all matches and then run it over all those (n^2 complexity)
//whatever you wanna do
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/479804.html
上一篇:如何從日期字串中洗掉“,”
