【问题标题】:php - regular expression matching first occurrencephp - 匹配第一次出现的正则表达式
【发布时间】:2013-11-19 03:25:39
【问题描述】:

我需要匹配以下模式的第一次出现,以 \s( 开头,然后是 NIC 后跟任何字符,后跟 #. 后跟 56 数字。

使用的正则表达式:

preg_match('/[\\s|(]NIC.*[#|.]\d{5,6}/i', trim($test), $matches1);

例子:

  1. $test = "(NIC.123456"; // 工作正常
  2. $test = "(NIC.123456 oldnic#65703 checking" // 产生结果 (NIC.123456 oldnic#65703

但它只需要是(NIC.123456。有什么问题?

【问题讨论】:

    标签: php regex


    【解决方案1】:

    您需要为非贪婪匹配添加? 量词。这里.* 匹配了尽可能多的数量。

    你也不需要在这里双重转义\\s,你可以只使用\s,你可以在你的字符类中组合选择性字符,而不是在管道中添加|分隔符。

    另请注意,您的表达式将匹配以下字符串 (NIC_CCC.123456,为避免这种情况,您可以使用单词边界 \b 匹配单词字符和非单词字符之间的边界。

    preg_match('/(?<=^|\s)\(nic\b.*?[#.]\d{5,6}/i', $test, $match);
    

    正则表达式:

    (?<=           look behind to see if there is:
     ^             the beginning of the string
      |            OR
     \s            whitespace (\n, \r, \t, \f, and " ")
    )              end of look-behind
    \(             '('
     nic           'nic'
     \b            the boundary between a word char (\w) and not a word char
     .*?           any character except \n (0 or more times)
      [#.]         any character of: '#', '.'
      \d{5,6}      digits (0-9) (between 5 and 6 times)
    

    live demo

    【讨论】:

      【解决方案2】:

      已尝试使用 $test1 = explode(" ", $test); 并使用 $test1[0] 显示您的结果。

      【讨论】:

        猜你喜欢
        • 2016-03-18
        • 2022-08-13
        • 2018-06-28
        • 2015-04-10
        • 1970-01-01
        • 2011-01-02
        • 2019-07-19
        相关资源
        最近更新 更多