我需要一個正則表達式來匹配除none以外的任何字符串。 我試過使用 regular exp =「^ [^ none] $」, 但它不起作用。java的正則表達式來接受任何字以外的任何字
回答
您可以使用正則表達式(?!^none$).*
。有關詳細信息,請參閱此問題:Regex inverse matching on specific string?
"^[^none]$"
不起作用的原因是您實際上匹配除字符串「n」,「o」或「e」之外的所有字符串。
當然,使用String.equals
會更容易:!"none".equals(testString)
。
正則表達式「^(?! none)。+ $」不接受字符串。正則表達式不應該不接受。它應該接受所有其他的話。我如何修改表達式? – user679526
@ user679526我現在明白了。 '^(?! none)。+ $'匹配任何不以「none」開頭的單詞。我用正則表達式'(?!^ none $)。*'編輯我的答案,它應該匹配除「無」以外的每個字符串。 –
如果要針對在Java中的特定單詞,你應該使用equals()
匹配String
。在這種情況下,您想要反轉匹配,以便您的邏輯變爲:
if(!theString.equals("none")) {
// do stuff here
}
更少的資源需求,更直觀。
如果您需要匹配包含單詞「無」的字符串,你可能尋找的東西,如:
if(theString.matches("\\bnone\\b")) {
/* matches theString if the substring "none" is enclosed between
* 「word boundaries」, so it will not match for example: "nonetheless"
*/
}
或者,如果你可以相當肯定的是,「單詞邊界」是指一個特定的符
int i = theString.indexOf("none");
if(i > -1) {
if(i > 0) {
// check theString.charAt(i - 1) to see if it is a word boundary
// e.g.: whitespace
}
// the 4 is because of the fact that "none" is 4 characters long.
if((theString.length() - i - 4) > 0) {
// check theString.charAt(i + 4) to see if it is a word boundary
// e.g.: whitespace
}
}
else {
// not found.
}
其實這是正則表達式匹配除「詞」一切話:
你仍然可以通過使用indexOf()
方法逃避的正則表達式
您必須使用單詞邊界,以便「單詞」不包含在其他字詞中。
說明:
"
\b # Assert position at a word boundary
(?! # Assert that it is impossible to match the regex below starting at this position (negative lookahead)
Lorem # Match the characters 「Lorem」 literally
\b # Assert position at a word boundary
)
\w # Match a single character that is a 「word character」 (letters, digits, etc.)
+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
\b # Assert position at a word boundary
"
這是你正在尋找的正則表達式:
Pattern p = Pattern.compile("^(?!none$).*$");
Matcher m = p.matcher("your string");
System.out.println(s + ": " + (m.matches() ? "Match" : "NO Match"));
雖這麼說,如果你沒有被迫使用匹配的一切,但「沒有一個正則表達式「,更簡單,快速,清晰,易於編寫和理解的是:
Pattern p = Pattern.compile("^none$");
然後,你只需排除比賽。
Matcher m = p.matcher("your string");
System.out.println(s + ": " + (m.matches() ? "NO Match" : "Match"));
- 1. 正則表達式接受任何字母任何語言,符號或數字
- 2. Lucene任何字母正則表達式
- 3. 正則表達式 - 任何字符
- 4. 正則表達式替換任何字符(數字/,除外)
- 5. 使用正則表達式接受用戶/鏈接後的任何字符串
- 6. php正則表達式匹配除數字以外的任何單詞字符
- 7. ruby正則表達式匹配除特定字符以外的任何字符
- 8. 如何用java正則表達式寫入任何字符串?
- 9. 如何在正則表達式中匹配[X以外的任何字符]?
- 10. 任何字符串的正則表達式不以.asp結尾
- 11. 任何語言的字字符的正則表達式
- 12. 接受一個額外字符的SSN的正則表達式
- 13. 正則表達式接受 - 字符
- 14. 正則表達式來獲得任何數字不僅整數
- 15. 正則表達式來解析任何CSS字體
- 16. 匹配任何unicode字母與java正則表達式
- 17. 如何使正則表達式接受字符串以點
- 18. 正則表達式 - 匹配除特定字符串以外的任何內容
- 19. 正則表達式以匹配除滿零之外的任何數字?
- 20. 使用正則表達式匹配除下劃線以外的任何字符
- 21. PHP正則表達式匹配除Example.com以外的任何URL
- 22. Java的正則表達式接受比
- 23. 正則表達式匹配高達「/」的任何字符串Javascript
- 24. 正則表達式任意ASCII字符
- 25. Java正則表達式以任何形式組合模式
- 26. 正則表達式以任何順序匹配字符串
- 27. jQuery - 正則表達式,以防止任何特殊字符
- 28. 正則表達式,匹配除這些字符串之外的任何字符
- 29. 正則表達式如何選擇「。」後面的任何字符。
- 30. Django的URL正則表達式不接受任何數字或任意數量的,直到99
你的意思是 「比 '沒有' 其他」?如果是這樣,爲什麼不匹配'無'並否定結果呢? –
如果你的字符串是「none」,你只想失敗嗎? – FailedDev