Regex for a fixed-length string, starting with a few words

I am trying to create a regular expression (JS flavor) that matches a string that is exactly 17 alphanumeric characters long and should start with "AB", "DE" or "GH". After these three possibilities, any alphanumeric character is accepted.

Match:

AB163829F13246915 DET639601BA167860 GHF1973771A002957 

Do not match

 XYZ63829F13246915 AAA639601BA167860 BBC1973771A002957 

So far, I have this regex that I'm testing at http://regexpal.com/

 ^(AB|)[a-zA-Z0-9]{17}$ 

Not sure why the pipe symbol is required to fit my first example or why it fails when I add "DE" after the channel.

Is anyone

+9
source share
7 answers

Use this:

 ^(AB|DE|GH)[a-zA-Z0-9]{15}$ 

The first two characters already occupy the two, so after that you need another 15 alphanumeric characters.

http://rubular.com/r/rAWmIy4Xeh

+12
source

You had it almost:

 (AB|DE|GH)[a-zA-Z0-9]{15} 

Demo

Since AB|DE|GH will already be 2 char long, only 15 should be allowed outside.

You can also use a group without capturing ( (?:AB|DE|GH)[a-zA-Z0-9]{15} ) and bind your template ( ^(?:AB|DE|GH)[a-zA-Z0-9]{15}$ ), if necessary.

+4
source

you can try the following:

 /^(?:AB|DE|GH)[A-Z0-9]{15}$/ 
+2
source

The current current regular expression searches for a string that can begin with s> AB , and then a few alphanumeric characters. If it starts with AB , the string length will be 19. Otherwise, it will be 17.

Obviously, this is not what you had in mind.

Try the following:

 /^(?=AB|DE|GH)[a-zA-Z0-9]{17}$/ 

This uses a lookahead statement to ensure that a line starts with the right combinations and then starts efficiently when it counts 17 characters.

0
source

Try the following:

 ^(AB|DE|GH)[a-zA-Z0-9]{15}$ 

Anything that matches (AB|DE|GH) will consume exactly two characters, so you need to change the repetition in the character class [a-zA-Z0-9] to 15.

Please note that this can also be reduced a little:

 ^(AB|DE|GH)[^\W_]{15}$ 

This works because \W matches everything except letters, numbers, and underscores. By putting \W and _ in a negative character class, you get an element that matches letters and numbers.

0
source

In your template, the pipe makes the first part of it coincide with either AB or an empty string. You have not excluded two characters from 17, so it must match an empty string to get the next 17 characters according to the rest of the pattern. The pattern will also match, for example, AB00000000000000000 , i.e. AB followed by 17 alphanumeric characters.

You must do this according to the combinations of two characters at the beginning, then 15 alphanumeric characters:

 ^(AB|DE|GH)[a-zA-Z0-9]{15}$ 
0
source

You can add a restriction below in xsd for a fixed-length alphabetical string.

 <xsd:restriction base="xsd:string"> <xsd:pattern value="[a-zA-Z0-9]{1,30}" /> 
0
source

Source: https://habr.com/ru/post/944994/


All Articles