簡體   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