Basic regex for 16 digit numbers

17,046

Solution 1

If all groups are always 4 digit long:

\b\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}\b

to be sure the delimiter is the same between groups:

\b\d{4}(| |-)\d{4}\1\d{4}\1\d{4}\b

Solution 2

If it's always all together or groups of fours, then one way to do this with a single regex is something like:

Regex.Match(l, @"\d{16}|\d{4}[- ]\d{4}[- ]\d{4}[- ]\d{4}")

Solution 3

You could try something like:

^([0-9]{4}[\s-]?){3}([0-9]{4})$

That should do the trick.

Please note: This also allows

1234-5678 9123 4567

It's not strict on only dashes or only spaces.

Share:
17,046
user1326461
Author by

user1326461

Updated on June 11, 2022

Comments

  • user1326461
    user1326461 almost 2 years

    I currently have a regex that pulls up a 16 digit number from a file e.g.:

    Regex:

    Regex.Match(l, @"\d{16}")
    

    This would work well for a number as follows:

    1234567891234567

    Although how could I also include numbers in the regex such as:

    1234 5678 9123 4567

    and

    1234-5678-9123-4567

  • LexyStardust
    LexyStardust about 12 years
    Would \b\d{4}([- ]?)\d{4}\1\d{4}\1\d{4}\b be more readable? The pipe after the empty string hurts my brain!
  • Toto
    Toto about 12 years
    Doesn't match when there're no delmiters, ie 1234567890123456
  • Toto
    Toto about 12 years
    @LexyStardust: It's just a matter of taste
  • LexyStardust
    LexyStardust about 12 years
    M42 agreed, Regexes are a window on the soul. Or something!
  • ΩmegaMan
    ΩmegaMan about 12 years
    True...but the OP needs to give us an example which demonstrated the need to work within a file...we shouldn't have to read their mind to figure out the multitude of permuations which could be the case.