Regular expression to validate a field

2

I have an input on the form that should only accept the following formats:

Examples

  • 1AB
  • 1AB2CD
  • 1AB2CD3EF

The minimum size must be 3 and maximum 9, and must always follow the pattern 1 digit and 2 letters. It should not be accepted for example 1AB2 or 1AB2C.

I did so:

[0-9]{1}[a-zA-Z]{2}

But in this case it only works for the first example I put, I do not know how to repeat the pattern.

    
asked by anonymous 05.06.2018 / 13:53

1 answer

1

If you want the "1 digit, 2 letter" pattern to be repeated a maximum of 3 times, you can use the {} quantizer, indicating the minimum and maximum number of times. In this case, the minimum is 1, and the maximum is 3, then it would look like:

(\d[a-zA-Z]{2}){1,3}

Notice that I changed [0-9] to \d , as are equivalent * (both are for digits). And I removed {1} because it is redundant, since "1 repetition" is the default.

And the parentheses are necessary, since the whole "1 digit, 2 letters" should be repeated 1 to 3 times.

You can see this regex running here .

* Usually < [0-9] and \d are equivalent. The only detail is that depending on the language / engine / configuration, \d may also correspond to other characters representing digits , such as ٠١٢٣٤٥٦٧٨٩ characters (see this answer for more details).

    
05.06.2018 / 14:10