【问题标题】:Regular Expressions pattern to extract particular digits from text [closed]从文本中提取特定数字的正则表达式模式[关闭]
【发布时间】:2012-05-13 00:49:13
【问题描述】:

我正在尝试使用 preg_match_all() 函数从 php 中的字符串中提取电话号码。我知道这种模式'!\d+!' 提取所有数字。但我需要它做更多。 我要提取的数字要么以 256 开头,然后是 9 个数字,要么以 078,077,071,079 开头,然后是 8 个数字。 谢谢。

【问题讨论】:

  • 那么到目前为止你尝试过什么?

标签: php regex preg-match-all


【解决方案1】:

我会使用:

(256\d|07[17-9])\d{8}

RegExr link

【讨论】:

  • 只使用\d{8}的聪明方法
  • 您的正则表达式周围缺少锚点。
  • @KurzedMetal,这也找到了 3 位数的捕获组(例如“078”),对吗?知道如何只返回完整的字符串吗?我正在使用这个在 JS Web 控制台中进行测试:"07800000000".match(/(256\d|078|077|071|079)\d{8}/);
  • 我刚刚意识到我的答案与 Cylian 的非常相似。
  • @stema 井锚很容易添加,他没有具体说明任何要求。我不知道它们是否应该从行首开始,是否用引号引起来或用空格分隔。
【解决方案2】:

我并不声称自己是正则表达式方面的专家,但我测试了一个可行的方法。

(^(256[0-9]{9})|^(078|077|071|079)[0-9]{8})

我尝试了以下方法:

256123456789
07812345678
07712345678
07112345678
07912345678
07212345678

注意最后一条不符合你所说的规则之一。输出与最后一个匹配。

【讨论】:

  • 这些括号不会导致它捕获“078”和其他 3 位模式作为匹配项吗?我也不是专家,但我试图弄清楚如何使用方括号以同样的方式做到这一点(运气不好)
  • 啊,是的,好点。我加入了 ^ 分隔符来表示行首。
  • 啊,它是分布式的,明白了,谢谢。
  • 只使用一个^,但在括号之外,您还需要锚点作为行尾$ ==> ^((256[0-9]{9})|(078|077|071|079)[0-9]{8})$
  • 我明白了,说也许他想匹配 256xxxx(以 256 开头的字符串)或匹配 xxx078xxxx(以任何东西开头的字符串),您是否将 ^ 放在 256 块后面?
【解决方案3】:

试试这个:

\b(?:256\d{9}|07[17-9]\d{8})\b

说明:

<!--
\b(?:256\d{9}|07[17-9]\d{8})\b

Options: ^ and $ match at line breaks; free-spacing

Assert position at a word boundary «\b»
Match the regular expression below «(?:256\d{9}|07[17-9]\d{8})»
   Match either the regular expression below (attempting the next alternative only if this one fails) «256\d{9}»
      Match the characters “256” literally «256»
      Match a single digit 0..9 «\d{9}»
         Exactly 9 times «{9}»
   Or match regular expression number 2 below (the entire group fails if this one fails to match) «07[17-9]\d{8}»
      Match the characters “07” literally «07»
      Match a single character present in the list below «[17-9]»
         The character “1” «1»
         A character in the range between “7” and “9” «7-9»
      Match a single digit 0..9 «\d{8}»
         Exactly 8 times «{8}»
Assert position at a word boundary «\b»
-->

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    相关资源
    最近更新 更多