Regex Exclude Number Within Two Characters of Number

Viewed 39

I have some manually entered data (it's an email subject), and I am trying to extract the correct ID to perform a series of actions with RPA on.

RE:'HC=312-822-281' abc2-1234567 7354612

I have a regex query:

(?<!\d)\d{7}(?!\d)

I want to extract 7354612 but not 1234567.

I want to avoid matching any 7-digit number that is preceded with a hyphen, or a hyphen and a space.

My initial query works 80% of the time, but this hyphen issue is interfering with the other 20%.

1 Answers

You can modify the existing (?<!\d) lookbehind to also exclude the position after a hyphen, i.e. (?<![\d-]), and add another lookbehind to exclude the hyphen + space context ((?<!- ) or (?<!-\s)):

(?<![\d-])(?<!- )\d{7}(?!\d)
(?<![\d-])(?<!-\s)\d{7}(?!\d)

Note \s matches any whitespace. See the regex demo.

Details

  • (?<![\d-]) - a negative lookbehind that fails the match if there is a digit or a hyphen immediately to the left of the current location
  • (?<!-\s) - a negative lookbehind that fails the match if there is a - and a space after it immediately to the left of the current location
  • \d{7} - any seven digits
  • (?!\d) - a negative lookahead that fails the match if there is a digit immediately to the right of the current location.

Variations

With PCRE regex, you may also use

-\s*\d{7}(?!\d)(*SKIP)(*F)|(?<!\d)\d{7}(?!\d)

See the regex demo, where -\s*\d{7}(?!\d)(*SKIP)(*F)| matches -, 0+ spaces, seven digits after which there are no more digits and skips that match, only returning matches for the (?<!\d)\d{7}(?!\d) pattern.

In .NET, modern JavaScript and PyPi regex in Python, you may use

(?<!\d|-\s*)\d{7}(?!\d)

See this regex demo. Here, (?<!\d|-\s*) negative lookbehind fails the match if there is a digit or - + 0 or more whitespace chars immediately to the left of the current position.

Related