簡體   English   中英

PHP 正則表達式匹配字符串中的所有單個字母后跟數字值

[英]PHP regex to match all single letters followed by numeric value in string

我正在嘗試為以下類型的字符串運行正則表達式:一個大寫字母后跟一個數值。 該字符串可以由多個這些字母-數字-值組合組成。 這里有一些例子和我預期的 output:

A12B8Y9CC10
-> output [0 => 12, 1 => 8, 2 => 9] (10 is ignored, because there are two letters)
V5C8I17
-> output [0 => 5, 1 => 8, 2 => 17]
KK18II9
-> output [] (because KK and II are always two letters followed by numeric values)
I8VV22ZZ4S9U2
-> output [0 => 8, 1 => 9, 2 => 2] (VV and ZZ are ignored)
A18Z12I
-> output [0 => 18, 1 => 12] (I is ignored, because no numeric value follows)

我嘗試使用 preg_match 通過以下正則表達式來達到此目的: /^([AZ]{1}\d{1,)$/

但它沒有給出預期的 output。 你能幫我嗎,如何解決這個問題?

謝謝和最好的問候!

您可以使用preg_match_allphp中使用此正則表達式:

preg_match_all('/(?<![a-zA-Z])[a-zA-Z]\K\d+/', $string, $matches);

導致數組$matches[0]返回所有匹配項。

正則表達式演示

正則表達式詳細信息:

  • (?<![a-zA-Z]) :確保我們在當前 position 之前沒有字母
  • [a-zA-Z] : 匹配一個字母
  • \K : 重置比賽信息
  • \d+ :匹配 1+ 個數字

另一種變體可能是使用SKIP FAIL來跳過不符合條件的匹配項。

[A-Z]{2,}\d+(*SKIP)(*FAIL)|[A-Z](\d+)

解釋

  • [AZ]{2,}\d+匹配 2 個或多個大寫字符 AZ 和 1+ 個數字
  • (*SKIP)(*FAIL)使用 SKIP FAIL 避免匹配
  • | 或者
  • [AZ](\d+)匹配單個字符 AZ 並在第 1 組中捕獲一位或多位數字

正則表達式演示| Php 演示

匹配是第一個捕獲組。

$pattern = '/[A-Z]{2,}\d+(*SKIP)(*FAIL)|[A-Z](\d+)/';
preg_match_all($pattern, $string, $matches);
print_r($matches[1]);

或者在anubhava的答案中使用\K

[A-Z]{2,}\d+(*SKIP)(*FAIL)|[A-Z]\K\d+

正則表達式演示| php 演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM