Home > Software design >  Regex : matches all 7 digit number except the one that starts with abc
Regex : matches all 7 digit number except the one that starts with abc

Time:05-01

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 is abc: 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
} 
  • Related