4

I'm new to RegEx and I'm trying to match a specific number that has 8 digits, and has 3 start options:

  • 00
  • 15620450000
  • VS

For Example:

  • 1562045000012345678
  • VS12345678
  • 0012345678
  • 12345678

I don't want to match the 4th option. Right now I have managed to match the first and third options, but I'm having problems with the second one, I wrote this expression, trying to match the 8 digits under 'Project':

156204500|VS|00(?<Project>\d{8})

What should I do?

Thanks

Eyal
  • 59
  • 3

2 Answers2

6

With your shown samples, please try following regex once.

^(?:00|15620450000|VS)(\d{8})$

OR to match it with Project try:

^(?:00|15620450000|VS)(?<Project>\d{8})$

Online demo for above regex

Explanation: Adding detailed explanation for above.

^(?:00|15620450000|VS)  ##Checking value from starting and in a non-capturing group matching 00/15620450000/VS here as per question.
(?<Project>\d{8}        ##Creating group named Project which is making sure value has only 8 digits till end of value.
)$                      ##Closing capturing group here.
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
4

Let's understand why your solution failed that will help you get around such kind of problems in the future. Your regex, 156204500|VS|00(\d{8}) is processed as follows:

156204500 OR VS OR 00(\d{8})

In arithmetic,

1 + 2 + 3 (4 + 5) <--- (4 + 5) is multiplied with only 3

is different from

(1 + 2 + 3) (4 + 5) <--- (4 + 5) is multiplied with (1 + 2 + 3)

This rule is applicable to RegEx as well. Obviously, you intended to use the second form.

By now, you must have already figured out the following solution:

(15620450000|VS|00)(\d{8})

Note that unless you want to capture a group, a capturing group does not make sense and this is where regex has another concept called non-capturing group which you obtain by putting ?: as the first thing in the parentheses. With a non-capturing group, the final solution becomes:

(?:15620450000|VS|00)\d{8}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110