【问题标题】:PHP regex to match all single letters followed by numeric value in stringPHP正则表达式匹配所有单个字母后跟字符串中的数值
【发布时间】:2020-10-15 19:27:33
【问题描述】:

我正在尝试为以下类型的字符串运行正则表达式:一个大写字母后跟一个数值。该字符串可以由多个这些字母-数字-值组合组成。这里有一些例子和我的预期输出:

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 通过以下正则表达式来达到此目的: /^([A-Z]{1}\d{1,)$/

但它没有给出预期的输出。你能帮我解决这个问题吗?

谢谢和最好的问候!

【问题讨论】:

    标签: php regex numbers preg-match letter


    【解决方案1】:

    另一种变体可能是使用SKIP FAIL 跳过不符合条件的匹配项。

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

    解释

    • [A-Z]{2,}\d+ 匹配 2 个或多个大写字符 A-Z 和 1+ 个数字
    • (*SKIP)(*FAIL) 使用 SKIP FAIL 避免匹配
    • |或者
    • [A-Z](\d+) 匹配单个字符 A-Z 并在 group 1 中捕获一个或多个数字

    Regex demo | Php demo

    匹配是第一个捕获组。

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

    或者使用\K,如anubhava 的回答

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

    Regex demo | php demo

    【讨论】:

      【解决方案2】:

      您可以在php 中使用此正则表达式preg_match_all

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

      导致数组$matches[0] 返回所有匹配项。

      RegEx Demo

      正则表达式详细信息:

      • (?&lt;![a-zA-Z]): 确保当前位置之前没有字母
      • [a-zA-Z]:匹配一个字母
      • \K: 重置比赛信息
      • \d+:匹配 1+ 个数字

      【讨论】:

      • 非常感谢阿努巴瓦!效果很好。您发布的代码中仅缺少左括号。必须看起来像这样: preg_match_all('/(?
      猜你喜欢
      • 1970-01-01
      • 2013-10-31
      • 1970-01-01
      • 2023-02-01
      • 2011-09-02
      • 2020-09-05
      • 2014-04-29
      • 2019-08-26
      • 2016-09-01
      相关资源
      最近更新 更多