简体   繁体   English

perl正则表达式正好10个字符

[英]perl regex of exactly 10 characters

I'm using perl flavored regexes in PHP with the preg_match function. 我在PHP中使用perl风格的正则表达式和preg_match函数。 I want to validate a key that is exactly 10 characters, with upper case alpha characters or numbers. 我想验证一个正好10个字符的密钥,大写字母字符或数字。

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? 如何指定此正则表达式?

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. /[^A-Z0-9]{10}$/将匹配所有以10个字符结尾的文件,这些字符不是大写字母和数字。

The correct RE would be: 正确的RE将是:

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 如果^由此而直发现[ ,它否定了比赛
      • AZ - uppercase letters AZ - 大写字母
      • 0-9 - digits 0-9位数
    • ] - end of a character class ] - 字符类的结尾
    • {10} - matches the previous character class 10 times {10} - 匹配前一个字符类10次
  • $ - matches the string till the end $ - 匹配字符串直到结束

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM