Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic regex for 16 digit numbers

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

like image 343
user1326461 Avatar asked Apr 20 '12 12:04

user1326461


People also ask

How do you specify a number range in regex?

Example: Regex Number Range 1-20 Range 1-20 has both single digit numbers (1-9) and two digit numbers (10-20). For double digit numbers we have to split the group in two 10-19 (or in regex: "1[0-9]") and 20. Then we can join all these with an alternation operator to get "([1-9]|1[0-9]|20)".

What is the regex for only numbers?

To get a string contains only numbers (0-9) we use a regular expression (/^[0-9]+$/) which allows only numbers.

Can you use regex on numbers?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.

Which regex matches one or more digits?

+: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits.


2 Answers

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
like image 169
Toto Avatar answered Oct 08 '22 04:10

Toto


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}")

like image 21
teukkam Avatar answered Oct 08 '22 04:10

teukkam