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.
Author by
user1326461
Updated on June 11, 2022Comments
-
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 about 12 yearsWould \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 about 12 yearsDoesn't match when there're no delmiters, ie 1234567890123456
-
Toto about 12 years@LexyStardust: It's just a matter of taste
-
LexyStardust about 12 yearsM42 agreed, Regexes are a window on the soul. Or something!
-
ΩmegaMan about 12 yearsTrue...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.