Regular Expression for numbers between certain ranges

Asked

Viewed 92 times

3

I needed to make a regular expression where I only accept the numbers of 11-14, 21-24, 31-34.

I made the following regular expression:

^\A[11-14|21-24|31-34]{2}$

It is working, but why are you also accepting the numbers of 41-44 ? I can’t understand or correct.

  • 4

    Have you tested ^\A[1-3][1-4]$?

  • Perfect, it worked right and much simpler. I never did Regular Expression in my life, first time, I searched today on the subject. Thank you very much.

  • 1

    Carlos and @anonimo - just remember what to use ^ and \A together does not make much sense (as I explain in my answer below - I just did not detail more because it is not the focus of the question)

1 answer

2


Simple, all the characters you put between brackets are actually a character class: a list of characters that must be accepted.

For example, [abc] means "the letter a, or b, or c" (any of them). And you can also specify ranges: [a-f] is "any letter of a to f".

So, [11-14|21-24|31-34] actually means "the digit 1, or a digit from 1 to 4 (1-4), or the character |, or the digit 2, etc.".

And how did you put the quantifier {2}, regex accepts 2 occurrences of that (i.e., 2 characters that are 1, or a digit from 1 to 4, or |, etc). So she accepts 44, and even || would be accepted (can test).

So the correct expression would be ^[1-3][1-4]$ (the first character is a digit from 1 to 3, and the second is a digit from 1 to 4).

Obs: Notice I removed the shortcut \A because it seems redundant, since the ^ indicates the start of the string, and the \A also (the difference is whether you use the multi-line mode, in which the ^ also considers the beginning of a line, but then you would have to choose between one or the other anyway, because both in the same expression - one right after the other - does not make sense).

  • 1

    Perfect @hkotsubo, thanks for the explanation, now I understand the concept, I thought putting with the | would be like a "or"... and it worked even the || you are right... rsrs It worked perfectly as you said, by the way, as the previous colleague commented worked in regex101 but it did not work in Google Forms, where I will use in this case. By removing the \A, worked perfectly. Thanks so much for the help.

  • 1

    @Carloshenriqueneveschneves O | means "or", but only if it is outside the brackets. Inside the brackets the metacharacters "lose their powers" and become "normal" characters".

  • Got @hkotsubo thanks for further clarification. I didn’t know there was difference being inside the brackets. Thanks.

Browser other questions tagged

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