繁体   English   中英

PHP正则表达式和preg_match

[英]PHP regex and preg_match

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

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

我需要在等号(=)和管道(|)符号之间出现的数字,或者行的末尾。 因此,在最后一个例子,我需要98322134411 ,但我不知道这一点的。 数字不具体,可以是任意数量的数字。

我只是学习正则表达式和preg_match而无法搞清楚。 我不知道我在做什么。

非常感谢任何帮助。

试试以下:

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

描述

这个表达式将:

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

\\d+(?=[,|\\n\\r]|\\Z) 现场演示

在此输入图像描述

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) 现场演示

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM