Search code examples
regexpcre

regex to match exactly 16 consecutive digits in a potentially larger string


I need a regular expression that will match exactly 16 consecutive digits, no more or less, regardless of what, if anything, is surrounding it. I've gone through a couple iterations but all have had issues:

  1. \d{16} will match any 16 consecutive digits, including 16 digits within a longer string of digits
  2. ^\d{16}$ will match a line that is exactly 16 consecutive digits, but if there is anything else in the string, the match will fail
  3. \D\d{16}\D will match a string of 16 consecutive digits, but only if it is surrounded by non-digit characters. If the string of 16 digits is alone on the line, it fails
  4. \D?\d{16}\D? will match a longer string of consecutive digits
  5. [\D^]\d{16}[\D$] does not treat ^ and $ as their special meanings, but rather treats them as literal characters.

How can I create the regex I need?

Edit: These are PCRE regex


Solution

  • You can use lookaround

    (?<!\d)\d{16}(?!\d)
    
    • (?<!\d) - Match should not be preceded by digit
    • \d{16} - Match digits (0 - 9) 16 times
    • (?!\d) - Match should not be followed by digit

    Regex demo