我想在空格分隔的數字列表中匹配單個'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
回顧後的長度是固定的,所以我很困惑,爲什麼這個正則表達式不匹配。如果您知道爲什麼和/或可以爲這種情況提供替代工作正則表達式,我將非常感激。
謝謝。
你什麼意思?也許我不是很清楚,當'1'被空白或沒有任何東西包圍時,我需要匹配......這給了我一個替代正則表達式的想法,但沒有回答爲什麼這個不起作用。 –