Home > Blockchain >  Why are backslashes matched by character classes not containing them in Regular Expressions?
Why are backslashes matched by character classes not containing them in Regular Expressions?

Time:02-03

I am trying to match an alphanumeric String in PHP 8.2 using preg_match.

$str = '\\\\';

echo preg_match("/^[A-z0-9]*$/", $str);

The output of the following code is 1, indicating that the pattern matches the subject. How is it possible, that the character class [A-z0-9] matches the backslashes, which are not contained in it?

CodePudding user response:

Your regex contains A-z which means any any character between 65 and 122 (ascii table). \ is 92 which falls within that range. A tool like regex101 can help clarify what is included in regexes

To fix update the regex to be /^[A-Za-z0-9]*$/ which specifies only letters or numbers

  • Related