PHP:包含 3-9 个字母和 5-50 个数字的字符串的正则表达式

问题描述 投票:0回答:2

如何在 PHP 中制作一个只接受 3-9 个字母(大写)和 5-50 个数字的正则表达式?

我不太擅长正则表达式。但这不起作用:

/[A-Z]{3,9}[0-9]{5,50}/

例如,它匹配

ABC12345
但不匹配
A12345BC

有什么想法吗?

php regex
2个回答
12
投票

这是一个经典的“密码验证”类型的问题。为此,“粗略的方法”是先行检查每个条件,然后我们匹配所有内容。

^(?=(?:[^A-Z]*[A-Z]){3,9}[^A-Z]*$)(?=(?:[^0-9]*[0-9]){5,50}[^0-9]*$)[A-Z0-9]*$

我将在下面解释这一点,但这里有一种变体,我将留给您弄清楚。

^(?=(?:[^A-Z]*[A-Z]){3,9}[0-9]*$)(?=(?:[^0-9]*[0-9]){5,50}[A-Z]*$).*$

让我们一块一块地看第一个正则表达式。

  1. 我们将正则表达式锚定在字符串 ^ 的头部和字符串 $ 断言的结尾之间,确保匹配(如果有)是整个字符串。
  2. 我们有两种前瞻:一种用于大写字母,一种用于数字。
  3. 在前瞻之后,
    [A-Z0-9]*
    匹配整个字符串(如果它仅包含大写 ASCII 字母和数字)。 (感谢@TimPietzcker 指出我在方向盘上睡着了,因为那里有一个点星。)

前瞻如何工作?

(?:[^A-Z]*[A-Z]){3,9}[^A-Z]*$)
断言在当前位置,即字符串的开头,我们能够匹配“任意数量的非大写字母字符,后跟单个大写字母”3到9次。这确保了我们有足够的大写字母。请注意,
{3,9}
是贪婪的,因此我们将匹配尽可能多的大写字母。但我们不想匹配超出我们希望允许的数量,因此在表达式通过
{3,9}
量化后,前瞻检查我们是否可以匹配“零个或任意数量”的非大写字母字符,直到结束字符串的,由锚点
$
标记。

第二个前瞻以类似的方式工作。

有关此技术的更深入说明,您可能需要仔细阅读本页有关 regex Lookarounds 的密码验证部分。

如果您感兴趣,这里是该技术的逐个解释。

^                      the beginning of the string
(?=                    look ahead to see if there is:
 (?:                   group, but do not capture (between 3 and 9 times)
  [^A-Z]*              any character except: 'A' to 'Z' (0 or more times)
   [A-Z]               any character of: 'A' to 'Z'
 ){3,9}                end of grouping
  [^A-Z]*              any character except: 'A' to 'Z' (0 or more times)
$                      before an optional \n, and the end of the string
)                      end of look-ahead
(?=                    look ahead to see if there is:
 (?:                   group, but do not capture (between 5 and 50 times)
  [^0-9]*              any character except: '0' to '9' (0 or more times)
   [0-9]               any character of: '0' to '9'
 ){5,50}               end of grouping
  [^0-9]*              any character except: '0' to '9' (0 or more times)
$                      before an optional \n, and the end of the string
)                      end of look-ahead
[A-Z0-9]*              any character of: 'A' to 'Z', '0' to '9' (0 or more times)
$                      before an optional \n, and the end of the string

4
投票

Lorem ipsum dolor sat amet,consectetur adipiscing elit。 Praesent quis aliquam Massa。 Vivamus id ullamcorper odio,nec placerat urna。 Nam vitae ante efficitur, varius sapien a, sodales nibh. 《Interdum etmalesuada》在福西布斯 (faucibus) 中以“ac ante ipsum primis”而闻名。 Donec hendrerit lacus ac enim lacinia lacinia。 Etiam turpis ligula, ultricies sed risus in, egestas consequat augue。 Vivamus pretium、lectus ac finibus tempus、purus augue vulputate Tellus、nec venenatis mi arcu vitae ante。 Pellentesque venenatis Tellus sed Fermentum pellentesque。暂停效力。在有效之前非 eleifend ultrices。前庭爱欲 urna,eleifend sed sagittis 坐 amet,suscipit ac arcu。 Morbi ante risus, iaculis quis rhoncus vel, interdum id ipsum。 Etiam 在 felis nec sem dignissim 前庭。

© www.soinside.com 2019 - 2024. All rights reserved.