Home > Net >  How to match only specific characters in a given string with regex?
How to match only specific characters in a given string with regex?

Time:01-11

I want to a specific value, the value that must have:

  • the length should be 11.

  • the first digit should be 0.

  • the second digit should be 1.

  • the third digit should be 0, 1, 2, 5.

  • then match any digit from the forth digit to the end.

  • if the third digit is 1, then the last two digits(10th, 11th) should be the same.

  • if the third digit is 2, the 8th, 9th digits should be the same.

Input string, and expected result.

01012345678          -----> allowed.
0101234a5678         -----> not allowed., letter exists.
01112345688          -----> allowed, 10th, 11st are the same
01112345677          -----> allowed, 10th, 11st are the same
01112345666          -----> allowed, 10th, 11st are the same
01112345689          -----> not allowed..10th, 11st different
01112345-678         -----> not allowed..hyphen exists.
01298765532          -----> allowed..8th, 9th are the same.
01298765732          -----> not allowed, 8th, 9th different.
01298765mm432        -----> not allowed, more than 11 chars.
01500011122          -----> allowed..
020132156456136      -----> not allowed..more than 11 digit.
01530126453333       -----> not allowed..more than 11 digit.
00123456789          -----> not allowed.. second digit.

This is my attempt at regex101,^01[0125][0-9]{8}$ https://regex101.com/r/cIcD0R/1 but it ignore specific cases also it works for specific cases.

CodePudding user response:

You could make use of an alternation with 2 capture groups and backreferences:

^01(?:[05]\d{8}|1\d{6}(\d)\1|2\d{4}(\d)\2\d\d)$

Explanation

  • ^ Start of string
  • 01 Match literally
  • (?: Non capture group for the alternatives
    • [05]\d{8} Match either 0 or 5 and 8 digits
    • | Or
    • 1\d{6}(\d)\1 Match 1, then 6 digits, capture a single digit in group 1 followed by a backreference to match the same digit
    • | Or
    • 2\d{4}(\d)\2\d\d Match 2, then 4 digits, capture a single digit in group 2 followed by a backrefence to match the same digit and match the last 2 digits
  • ) Close the non capture group
  • $ End of string

See a regex101 demo

CodePudding user response:

With your shown samples please try following regex. Here is the Online Demo for used regex.

^01(?:[05][0-9]{8}|(?:1[0-9]{6}([0-9])\1)|(?:2[0-9]{4}([0-9])\2[0-9]{2}))$
  • Related