2014-03-06 48 views
2

我想在空格分隔的數字列表中匹配單個'1'。下面是一些示例代碼:爲什麼這個消極lookbehind固定長度的正則表達式不起作用?

public class RegexTester { 
    public static void main(String[] args) { 

    String test1 = "1 2"; 
    String test2 = "2 1 2"; 
    String test3 = "2 11 2"; 

    String regex = "(?<!\\d)1(?!\\d)"; 

    System.out.println("Matches 1: " + test1.matches(regex)); 
    System.out.println("Matches 2: " + test2.matches(regex)); 
    System.out.println("Matches 3: " + test3.matches(regex)); 
    } 
} 

輸出是:

Matches 1: false 
Matches 2: false 
Matches 3: false 

但應該是(IMO):

Matches 1: true 
Matches 2: true 
Matches 3: false 

回顧後的長度是固定的,所以我很困惑,爲什麼這個正則表達式不匹配。如果您知道爲什麼和/或可以爲這種情況提供替代工作正則表達式,我將非常感激。

謝謝。

+0

你什麼意思?也許我不是很清楚,當'1'被空白或沒有任何東西包圍時,我需要匹配......這給了我一個替代正則表達式的想法,但沒有回答爲什麼這個不起作用。 –

回答

2

你的正則表達式是正確的。問題是matches方法檢查整個輸入字符串是否可以通過正則表達式匹配,而不是如果它包含可以通過正則表達式匹配的子字符串。

也許使用find()方法從Matcher類代替。

String test1 = "1 2"; 
String test2 = "2 1 2"; 
String test3 = "2 11 2"; 

String regex = "(?<!\\d)1(?!\\d)"; 
Pattern p = Pattern.compile(regex); 

System.out.println("Matches 1: " + p.matcher(test1).find()); 
System.out.println("Matches 2: " + p.matcher(test2).find()); 
System.out.println("Matches 3: " + p.matcher(test3).find()); 

輸出:

Matches 1: true 
Matches 2: true 
Matches 3: false 

更新:

如果你真的需要使用matches那麼你可以在你的正則表達式的開始和結束添加.*所以部分旁邊需要一個能也被正則表達式消耗。

String regex = ".*(?<!\\d)1(?!\\d).*"; 

System.out.println("Matches 1: " + test1.matches(regex)); 
System.out.println("Matches 2: " + test2.matches(regex)); 
System.out.println("Matches 3: " + test3.matches(regex)); 

輸出:

Matches 1: true 
Matches 2: true 
Matches 3: false 
+0

啊,你說得對。我仍然需要找到一個替代方案,但我正在使用使用'match'的庫代碼。謝謝,我會盡快接受答案。 –

相關問題