Home > Blockchain >  Regex to match a string containing 14 digits and 1 character at any position
Regex to match a string containing 14 digits and 1 character at any position

Time:01-12

I need a regular expression that matches a string of 15 characters where 14 of them are digits and 1 is a character. The character can be in any position of the string.

I have the following long regex:

^.\d{14}|\d{1}.\d{13}|\d{2}.\d{12}|\d{3}.\d{11}|\d{4}.\d{10}|\d{5}.\d{9}|\d{6}.\d{8}|\d{7}.\d{7}|\d{8}.\d{6}|\d{9}.\d{5}|\d{10}.\d{4}|\d{11}.\d{3}|\d{12}.\d{2}|\d{13}.\d{1}|\d{14}.$

Can it be simplified?

Here is a sample match: 1000-1234567890

CodePudding user response:

We can use a lookaround trick here:

^(?!(?:.*\D){2})(?=.{15}$)\d*\D\d*$

This regex pattern says to match:

  • ^ from the start of the string
  • (?!(?:.*\D){2}) assert that 2 or more non digits do NOT occur (implying at most 1 occurs)
  • (?=.{15}$) assert length is 15 characaters
  • \d*\D\d* then a non digit surrounded, possibly, on either side by numbers
  • $ end of the string

CodePudding user response:

(?=^.{15}$)\d{0,14}\D\d{0,14}

First check the string is 15 characters long, then has 0-14 digits, one non-digit, then 0-14 digits.
This isn't exactly the same as the original regex, which allows 15 digits in a row. To get that, simply change \D to .

  • Related