php - PHP正则表达式匹配所有单个字母,后跟字符串中的数值
问题描述
我正在尝试为以下类型的字符串运行正则表达式:一个大写字母后跟一个数值。该字符串可以由多个这些字母-数字-值组合组成。这里有一些例子和我的预期输出:
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,)$/
但它没有给出预期的输出。你能帮我吗,如何解决这个问题?
谢谢和最好的问候!
解决方案
另一种变体可能是使用SKIP FAIL来跳过不符合条件的匹配项。
[A-Z]{2,}\d+(*SKIP)(*FAIL)|[A-Z](\d+)
解释
[A-Z]{2,}\d+
匹配 2 个或更多大写字符 AZ 和 1+ 个数字(*SKIP)(*FAIL)
使用 SKIP FAIL 避免匹配|
或者[A-Z](\d+)
匹配单个字符 AZ 并在组 1中捕获一个或多个数字
匹配是第一个捕获组。
$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+
推荐阅读
- javascript - 如果“密码”正是需要的,则打开网站(github页面)
- python - 具有聚合目标函数/具有软限制的目标的多背包问题
- python-3.x - 了解 Cpython 垃圾收集生成
- javascript - ScrollToOptions 的行为:Chrome 和 Edge v81+ 中的“平滑”中断
- python - 为什么在 Opencv 上使用 fitEllipse 时长轴长度的结果高于高度值?
- excel - 在用户窗体中以方程式样式编写文本
- c# - 指定 XML 文档输出路径的部署路径
- sql-server - 遍历一个表,将结果传递给一个 html 表以发送电子邮件?
- java - @Configuration @Bean 和 @RestController 注解的区别
- python - Django:如何通过 django 视图下载 .xls 文件