【问题标题】:PHP regex and preg_matchPHP 正则表达式和 preg_match
【发布时间】:2013-08-30 02:11:10
【问题描述】:

我有一个字符串需要匹配,可以是多种格式:

5=33
5=14,21
5=34,76,5
5=12,97|4=2
5=35,22|4=31,53,71
5=98,32|7=21,3|8=44,11

我需要出现在等号 (=) 和竖线 (|) 符号之间或行尾的数字。所以在最后一个例子中,我需要98,32,21,3,44,11 但我根本想不通。这些数字不是具体的,它们可以是任意数量的数字。

我只是在学习 regex 和 preg_match 并且无法弄清楚。我不知道我在做什么。

非常感谢任何帮助。

【问题讨论】:

    标签: php regex preg-match


    【解决方案1】:

    试试下面:

    preg_match_all('/(?<==)[^|]*/', $string, $matches);
    var_dump($matches);
    

    【讨论】:

      【解决方案2】:

      说明

      这个表达式将:

      • 只匹配数字
      • 要求数字在数字后直接有逗号、竖线或字符串结尾,这样可以防止包含等号的数字。

      \d+(?=[,|\n\r]|\Z)Live Demo

      NODE                     EXPLANATION
      --------------------------------------------------------------------------------
        \d+                      digits (0-9) (1 or more times (matching
                                 the most amount possible))
      --------------------------------------------------------------------------------
        (?=                      look ahead to see if there is:
      --------------------------------------------------------------------------------
          [,|\n\r]                 any character of: ',', '|', '\n'
                                   (newline), '\r' (carriage return)
      --------------------------------------------------------------------------------
         |                        OR
      --------------------------------------------------------------------------------
          \Z                       before an optional \n, and the end of
                                   the string
      --------------------------------------------------------------------------------
        )                        end of look-ahead
      

      示例

      样本

      使用此表达式,字符串5=98,32|7=21,3|8=44,11 将返回一个字符串数组:

      [0] => 98
      [1] => 32
      [2] => 21
      [3] => 3
      [4] => 44
      [5] => 11
      



      或者

      您可以只查找所有后面没有等号的数字

      \d+(?!=|\d)Live Demo

      【讨论】:

        猜你喜欢
        • 2013-04-05
        • 2014-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-27
        • 2012-01-14
        相关资源
        最近更新 更多