Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl regex of exactly 10 characters

Tags:

regex

php

pcre

I'm using perl flavored regexes in PHP with the preg_match function. I want to validate a key that is exactly 10 characters, with upper case alpha characters or numbers.

I have

preg_match( '/[^A-Z0-9]/', $key);

which finds invalid characters next to valid ones. In my limited knowledge, I tried

preg_match( '/[^A-Z0-9]{10}$/', $key);

which turns out to match all my test strings, even the invalid ones.

How do I specify this regular expression?

like image 490
user151841 Avatar asked Jan 19 '23 09:01

user151841


1 Answers

You've misplaced the ^ character which anchors the beginning of a string. /[^A-Z0-9]{10}$/ would match all files ending on 10 characters that are not uppercase letters and digits.

The correct RE would be:

preg_match( '/^[A-Z0-9]{10}$/', $key);

Explanation of the regexp:

  • ^ - matches from the beginning of the string
    • [ - begin of a character class, a character should match against these. If a ^ is found straight after this [, it negates the match
      • A-Z - uppercase letters
      • 0-9 - digits
    • ] - end of a character class
    • {10} - matches the previous character class 10 times
  • $ - matches the string till the end
like image 109
Lekensteyn Avatar answered Jan 28 '23 04:01

Lekensteyn