我正在尋找一個 java 正則運算式來匹配這樣的隨機字串:
Apple for Apple
day for day
Money for Money
... etc.
因此,如果前后有一個“for”和一個相同的單詞,正則運算式應該匹配字串。
目前我正在使用這個正則運算式:
[A-Za-z] [ ]{1}(for){1}[ ]{1}[A-Za-z]
但它也會回傳錯誤的結果,例如:
Apple for all
day for night
... etc.
我想只用正則運算式來完成這個,不需要額外的 Java 代碼。這可能嗎?
uj5u.com熱心網友回復:
您可以使用組來匹配“for”之前和之后的單詞。
試試這個:^(\\w ) for \\1
是的,那些是 for 之間的空格,你也可以使用 '\s' 但它會匹配所有的空格字符,如 \n、\r、\t 等。
解釋:
^(\\w ) for \\1
^ beginning of the string
(\\w ) capture group to catch any word
matches white space
for matches 'for'
matches white space
\\1 matches the word captured in the first capture group
在此處測驗正則運算式:https ://www.regexplanet.com/share/index.html?share=yyyyp3haukr
在這里:https ://regex101.com/r/wJvwob/1
uj5u.com熱心網友回復:
您可以String#matches()在此處使用反向參考:
List<String> inputs = Arrays.asList(new String[] {"Apple for Apple", "Apple for Orange"});
for (String input : inputs) {
if (input.matches("(\\w ) for \\1")) {
System.out.println("MATCH : " input);
}
else {
System.out.println("NO MATCH: " input);
}
}
這列印:
MATCH : Apple for Apple
NO MATCH: Apple for Orange
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/426711.html
上一篇:如何解決“org.openqa.selenium.support.ui.UnexpectedTagNameException:元素應該是“選擇”但是“輸入””硒錯誤
