【问题标题】:Regex where a number can start with 9 but not 999 consecutively正则表达式,其中一个数字可以连续以 9 开​​头,但不能以 999 开头
【发布时间】:2016-09-11 19:58:03
【问题描述】:

我正在尝试制作一个正则表达式,其中:

  1. 数字可以从 3、5、6 或 9 开始
  2. 号码不能以 999 开头。

例如,93214211 匹配,但 99912345 不应该匹配。

这是我现在满足第一个要求的:

^3|^5|^6|^9|[^...]}

我暂时停留在第二个要求上。 谢谢!

【问题讨论】:

  • 99321421呢?

标签: php regex pcre


【解决方案1】:

你可以用negative lookahead点赞

^(?!999)[3569]\d{7}$ <-- assuming the number to be of 8 digits

Regex Demo

正则表达式分解

^ #Start of string
  (?!999) #Negative lookahead. Asserts that its impossible to match 999 in beginning
  [3569] #Match any of 3, 5, 6 or 9
  \d{7} #Match 7 digits
$ #End of string

【讨论】:

  • 感谢您的快速回复!!你编辑之前的前一个就足够了,因为我在我的 cakephp 程序中添加了一个条件来验证 maxLength 为 8。
  • @AlfonsoKhiew 现在您可以在没有条件的情况下使用给定的正则表达式检查 8 位数字。
  • 只是为了好玩,一个类似的带有后视的正则表达式:^[3569]\d{2}(?&lt;!9{3})\d{5}$
猜你喜欢
  • 1970-01-01
  • 2017-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多