regex lookbehind with a date

Viewed 59

I fail to solve following problem:

I need to extract the 7 digit number (e.g. 2774800) in the middle of a string with regex. This is from an invoice. In each invoice I have a different 7-digit number. The product description also always changes, only the date always stays like dd.mm.yyyy, so I would use this as indicator and do a lookbehind search for the 7-digit number, but I can't get that to work.

Product description that always changes (sometimes here is a bracket) 2774800 21.11.2014

What I used to indicate the date is:

((0[1-9]|[12]\d|3[01]).(0[1-9]|1[0-2]).[12]\d{3})

For the 7 digit:

(?=\d{7}\s)\d+

I can't get them to work together correctly, so that the indicator is the date and it matches the 7-digit number.

1 Answers

You may use

\b\d{7}(?=\s+(?:0[1-9]|[12]\d|3[01])\.(?:0[1-9]|1[0-2])\.[12]\d{3})

See the regex demo.

Or, to match 6 to 8 digit numbers:

\b\d{6,8}(?=\s+(?:0[1-9]|[12]\d|3[01])\.(?:0[1-9]|1[0-2])\.[12]\d{3})

Details

  • \b - word boundary
  • \d{7} - seven digits
  • (?=\s+(?:0[1-9]|[12]\d|3[01])\.(?:0[1-9]|1[0-2])\.[12]\d{3}) - a positive lookahead that requires 1+ whitespaces and then a date-like pattern immediately to the right of the current location.
Related