Help with Regex

6

Before asking I looked for several references, but I still do not understand much and managed to reach only to a certain extent.

My goal is to validate that a specific string has 10 characters, the first two letters being uppercase, and the other 8 character numbers.

The first two letters should be obligatorily AD, AG, or EX. They can not be AE or EG for example.

For this I have the following Regex /^[A(D|G)|EX]{2}[0-9]{8}$/gm . But it does not fulfill the second rule. It allows the letters AGDEX to be mixed, not in the specific order desired.

I'm using RegExr to validate my regex with the following values:

EX09551115
AD09551115
AG09551115

EA09551115
EG09551115
AE09551115
AX09551115
DG09551115
GD09551115
XE09551115
GA09551115
DA09551115
XD09551115
XG09551115
GX09551115
DX09551115

Only values in bold should be valid values.

What I desire is to know how I do to satisfy the second condition. You do not have to leave a regex ready, just showing me the way will be a great help.

References are also welcome.

    
asked by anonymous 27.01.2016 / 14:06

3 answers

9

I believe that this regex ^(AD|AG|EX)[0-9]{8}$ or ^(AD|AG|EX)\d{8}$ solves the problem.

At the beginning of the line is expected (a group option) AD or AG or EX followed by numbers that should repeat exactly 8 times.

In a list the metacharacters lose their functions [A(D|G)|EX]{2} soon the group and OU (pipe) and you expect this to happen exactly twice.

    
27.01.2016 / 14:11
2

Oops, try this regex: link

Your regex /^[A(D|G)|EX]{2}[0-9]{8}$/gm did not work because you did not group the letters AD, AG, and EX, leaving A free together with D, G, and EX within the group.

A second option would be link , you can also use $ and ^ to define rows if you prefer.

    
27.01.2016 / 14:12
1

This works:

/^(AG|AD|EX)(\d{8})$/gm

Here's where groups in regular expression make sense:
First group is a combination of capital letters like AG or AD or EX ;
Second group is a sequence of digits having the size 8.

    
27.01.2016 / 14:20