The other answers suggested using \w
, which actually accepts alphanumeric characters (letters or numbers), but also accepts the character _
.
Does that mean that ^\w{32}_v2$
also considers a string that has 32 characters valid _
before _v2
(that is, the string _________________________________v2
would be considered valid). See here this regex working.
If that’s what you want, fine. But you want to limit yourself to only 32 letters and numbers (and not accept any other _
before _v2
), change the regex to ^[a-zA-Z0-9]{32}_v2$
. Behold here the difference.
The clasps ([]
) represent a character class. This means that any character within them serves. [ab]
, for example, it means "the letter a
or the letter b
" (any of them serve).
In case, I put inside the brackets the shortcuts a-z
(any letter of a
to z
), A-Z
(any letter of A
to Z
) and 0-9
(any digit of 0
to 9
). That is to say, [a-zA-Z0-9]
will accept only these characters, while \w
also accepts the character _
(the \w
is nothing more than a shortcut for [A-Za-z0-9_]
).
PS: depending on the language/engine/configuration, \w
can be even more comprehensive. For example, if the Unicode option is enabled, it can accept Japanese, Arabic and many other characters. (see examples here and here).
Usually this option is not enabled by default, but if you want to ensure that only letters from our alphabet and digits from 0 to 9 are accepted, use [a-zA-Z0-9]
.
\w
can accept all the cases you need, but also accepts others you may not need (strings with _
before _v2
). Again, if that’s not a problem, then use \w
. But if this is a problem and you want to avoid these false positives, be as specific as possible and use [a-zA-Z0-9]
.
It is unclear whether you want "exactly 32 characters" or "1 to 32 characters" before the _v2
. Anyway, just change the regex according to what you need:
- exactly 32 characters:
^[a-zA-Z0-9]{32}_v2$
- from 1 to 32 characters:
^[a-zA-Z0-9]{1,32}_v2$
+1 for not using
\w
and erroneously add the_
valid characters.– fernandosavio
@fernandosavio That’s right, these shortcuts (like
\w
and\d
) are very useful, but also hide these little "traps" (I myself have fallen into some...)– hkotsubo