ex: abc:1234567,cd:2345678,efg:3456789012
expected outcome 2345678
I tried
(?!abc)\d{7,7}
my result: 1234567
CodePudding user response:
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
}