'Regex : matches all 7 digit number except the one that starts with abc
ex: abc:1234567,cd:2345678,efg:3456789012
expected outcome 2345678
I tried
(?!abc)\d{7,7}
my result: 1234567
Solution 1:[1]
You can use
\b(?<!abc:)\d{7}\b
(?<!\d)(?<!abc:)\d{7}(?!\d)
See the regex demo.
Details:
\b- word boundary ((?<!\d)makes sure there is no other digit immediately to the left of the current location)(?<!abc:)- a negative lookbehind that fails the match if there isabc:immediately to the left of the current location\d{7}- seven digits\b- word boundary ((?!\d)makes sure there is no other digit immediately to the right of the current location).
See the Java demo:
String s = "abc:1234567,cd:2345678,efg:3456789012";
Pattern pattern = Pattern.compile("\\b(?<!abc:)\\d{7}\\b");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
System.out.println(matcher.group()); // => 2345678
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wiktor Stribiżew |
