【问题标题】:Regex HTML or PHP正则表达式 HTML 或 PHP
【发布时间】:2015-04-24 15:30:20
【问题描述】:

我需要在输入中对识别号进行正则表达式验证, 但它有两种格式(XX.XXX.XXX 或 X.XXX.XXX.XXX),X 只是数字。

我需要一种可以自动设置点并检测其格式的格式。

现在我得到了这个:

[1-9]{1,2}[.][0-9]{3}[.][0-9]{3} 
and {1-9}[.][0-9]{3}[.][0-9]{3}[.][0-9]{3}

【问题讨论】:

  • '设置点' - 您的验证输入是否带有点?

标签: javascript php jquery html regex


【解决方案1】:

指定备选方案:

^([1-9]{2}[.][0-9]{3}[.][0-9]{3}|[1-9][.][0-9]{3}[.][0-9]{3}[.][0-9]{3})$

编辑

添加了锚点。这些在这里是必不可少的!

【讨论】:

  • 我不知道你能做到,我去试试
  • 与 X.XXX.XXX.XXX 不匹配
【解决方案2】:

我可能想使用类似的东西:

if (preg_match('/^([\d]{2}\.[\d]{3}\.[\d]{3}|^[\d]{1}\.[\d]{3}\.[\d]{3}\.[\d]{3})/', $mynumbers)) {
    # Successful match
} else {
    # Match attempt failed
}

它将匹配2组带数字的字符串:

DD.DDD.DDDD.DDD.DDD.DDD

DEMO

正则表达式解释:

^([\d]{2}\.[\d]{3}\.[\d]{3}|^[\d]{1}\.[\d]{3}\.[\d]{3}\.[\d]{3}?)

Assert position at the beginning of a line (at beginning of the string or after a line break character) (line feed) «^»
Match the regex below and capture its match into backreference number 1 «([\d]{2}\.[\d]{3}\.[\d]{3}|^[\d]{1}\.[\d]{3}\.[\d]{3}\.[\d]{3}?)»
   Match this alternative (attempting the next alternative only if this one fails) «[\d]{2}\.[\d]{3}\.[\d]{3}»
      Match a single character that is a “digit” (any decimal number in any Unicode script) «[\d]{2}»
         Exactly 2 times «{2}»
      Match the character “.” literally «\.»
      Match a single character that is a “digit” (any decimal number in any Unicode script) «[\d]{3}»
         Exactly 3 times «{3}»
      Match the character “.” literally «\.»
      Match a single character that is a “digit” (any decimal number in any Unicode script) «[\d]{3}»
         Exactly 3 times «{3}»
   Or match this alternative (the entire group fails if this one fails to match) «^[\d]{1}\.[\d]{3}\.[\d]{3}\.[\d]{3}?»
      Assert position at the beginning of a line (at beginning of the string or after a line break character) (line feed) «^»
      Match a single character that is a “digit” (any decimal number in any Unicode script) «[\d]{1}»
         Exactly once (meaningless quantifier) «{1}»
      Match the character “.” literally «\.»
      Match a single character that is a “digit” (any decimal number in any Unicode script) «[\d]{3}»
         Exactly 3 times «{3}»
      Match the character “.” literally «\.»
      Match a single character that is a “digit” (any decimal number in any Unicode script) «[\d]{3}»
         Exactly 3 times «{3}»
      Match the character “.” literally «\.»
      Match a single character that is a “digit” (any decimal number in any Unicode script) «[\d]{3}?»
         Exactly 3 times «{3}?»

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2010-09-12
    • 1970-01-01
    相关资源
    最近更新 更多