Regex to validate a 5-digit alphanumeric field

Asked

Viewed 699 times

2

I’m doing a regular expression to validate an alphanumeric field of up to five digits. The first field should be numerical only, the rest can be letters or numbers:

ex: 1A, 11A, 111A, 1111A, 1, 11, 111, 1111, 11111

Restrictions:

  • There can’t be a letter between two numbers: ex = 1A11, 2A2, 222A1;
  • You can’t start with a letter: ex = A11;
  • There can be no letter followed by letter: ex = AA, AA1, A1A;

What I did first: \d?\w?\w?\w\w

It only accepts from the second character whether it is letter or number. This should not happen, because the first should be exclusively number. And accepts letters between numbers.

Then I came to it: ^(\d{0,5})([A-Z]{0,5})$

Here the only problem is that it accepts to start with letter and put letter followed by letter.

1 answer

3


\d{0,5} means "from zero to 5 digits". But from what I understand, you want it to have at least one digit at the beginning, so could change to \d{1,5} (between 1 and 5 digits).

But if we look at the rules, we see that a letter cannot be in the beginning or in the middle, and cannot have two letters in a row, so it can only be at the end (and can only have at most one). So actually you need the string to have the following:

  • has between 1 and 4 digits
  • followed (optionally) by a digit or a letter

Then you could use ^\d{1,4}[A-Z\d]?$.

The delimiters ^ and $ are respectively the beginning and end of the string. So I guarantee that the string only has what is in regex.

Then we have \d{1,4} (between 1 and 4 digits). Next, [A-Z\d]? means "a letter of A to Z or a digit", and the ? makes this section optional (see here this regex working).

Testing:

let r = /^\d{1,4}[A-Z\d]?$/;

let strings = ["1A", "11A", "111A", "1111A", "1", "11", "111", "1111", "11111", "1A11", "2A2", "222A1", "A11", "AA", "AA1", "A1A"];

// r.test retorna "true" se a string está de acordo com a regex
strings.forEach(s => console.log(s, '=', r.test(s)));


One detail is that [A-Z\d] only accepts uppercase letters. If you also want to consider lowercase, just switch to [A-Za-z\d].

And use \w is not a good option, because this shortcut, besides considering letters and numbers, it also considers the character _.

Browser other questions tagged

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