Regular expression to validate a field

Asked

Viewed 84 times

2

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

Examples

  • 1AB
  • 1AB2CD
  • 1AB2CD3EF

The minimum size has to be 3 and the maximum 9, and always follow the standard 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 only works for the first example I put, I do not know how to repeat the pattern.

  • 2

    Do you have any code you have started to write to try to solve your problem? Show it to us.

  • I did so: [0-9]{1}[a-za-Z]{2} But in this case only works for the first example I put, I do not know how to repeat the pattern

1 answer

1


If you want the "1 digit, 2 letters" pattern to repeat at most 3 times, you can use the quantifier {}, indicating the minimum and maximum amount of times. In case, the minimum is 1, and the maximum is 3, then would be:

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

Notice that I changed [0-9] for \d, for are equivalent* (both serve for digits). And removed the {1} because it’s redundant, since "1 repeat" is the standard ([0-9]{1} is the same as [0-9]).

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

You can see this regex working here.


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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.