2011-12-06 26 views
1

我需要一個正則表達式來匹配除none以外的任何字符串。 我試過使用 regular exp =「^ [^ none] $」, 但它不起作用。java的正則表達式來接受任何字以外的任何字

+0

你的意思是 「比 '沒有' 其他」?如果是這樣,爲什麼不匹配'無'並否定結果呢? –

+0

如果你的字符串是「none」,你只想失敗嗎? – FailedDev

回答

1

您可以使用正則表達式(?!^none$).*。有關詳細信息,請參閱此問題:Regex inverse matching on specific string?

"^[^none]$"不起作用的原因是您實際上匹配除字符串「n」,「o」或「e」之外的所有字符串。

當然,使用String.equals會更容易:!"none".equals(testString)

+0

正則表達式「^(?! none)。+ $」不接受字符串。正則表達式不應該不接受。它應該接受所有其他的話。我如何修改表達式? – user679526

+0

@ user679526我現在明白了。 '^(?! none)。+ $'匹配任何不以「none」開頭的單詞。我用正則表達式'(?!^ none $)。*'編輯我的答案,它應該匹配除「無」以外的每個字符串。 –

1

如果要針對在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. 
} 
0

其實這是正則表達式匹配除「詞」一切話:

你仍然可以通過使用 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 
" 
0

這是你正在尋找的正則表達式:

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")); 
相關問題