Home > Software engineering >  Using Regular Expression to validate the following requirement?
Using Regular Expression to validate the following requirement?

Time:01-07

i am trying to validate a number exactly 15 digits with 5 digits group separated by "-" , ":" , "/", that should start with either 5 or 4 or 37, it also should not contain any characters.

It means

37344-37747-27744 - valid
40344-37747-27744 - valid
59344-37747-27744 - valid
37344:37747:27744 - valid
37344/37747/27744 - valid
87887-98734-83422 - Not valid
548aa:aa764:90887 - not valid
37759\29938\92093 - not valid

I was only able to go this far


\d{5}[-:\/]\d{5}[-:\/]\d{5}

Please help.

CodePudding user response:

Try this one:

(((5|4)\d{4})|((37)\d{3}))[-:\/]\d{5}[-:\/]\d{5}

https://regex101.com/r/VvTq5P/1

Edit:

I would also add: \b at the beggining and at the end:

\b(((5|4)\d{4})|((37)\d{3}))[-:\/]\d{5}[-:\/]\d{5}\b

so nothing like:

12337344-37747-27744

can pass the test.

CodePudding user response:

You could use look ahead (?=.) to first check if your string starts ^ with numbers 5|4|37 that is the requirement, here's full pattern:

^(?=5|4|37)\d{5}[-:\/]\d{5}[-:\/]\d{5}$

Demo here

CodePudding user response:

If I understand correctly the regex is this:

((5|4)\d{4}|37\d{3})[-:\/]\d{5}[-:\/]\d{5}

Needs to be

4XXXX, 5XXXX or 37XXX

So I split it up to accept the 3 forms

CodePudding user response:

((5|4)\d{4}|37\d{3})[-:\/]\d{5}[-:\/]\d{5}

(5|4)\d{4} - looks for a number that starts with either 5 or 4 and four digits afterward.

Then the or 37\d{3} looks for 37 and three digits afterward.

  • Related