Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP正则表达式匹配字符串中的所有单个字母和数字值_Php_Regex_Numbers_Preg Match_Letter - Fatal编程技术网

PHP正则表达式匹配字符串中的所有单个字母和数字值

PHP正则表达式匹配字符串中的所有单个字母和数字值,php,regex,numbers,preg-match,letter,Php,Regex,Numbers,Preg Match,Letter,我试图让正则表达式为以下类型的字符串运行:一个大写字母后跟一个数值。字符串可以由多个字母数字值组合组成。下面是一些示例和我的预期输出: 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 -> outpu

我试图让正则表达式为以下类型的字符串运行:一个大写字母后跟一个数值。字符串可以由多个字母数字值组合组成。下面是一些示例和我的预期输出:

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$/

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

感谢并致以最诚挚的问候!

您可以使用preg\u match\u all在php中使用此正则表达式:

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

正则表达式详细信息:

?:确保我们在当前职位之前没有收到信函 [a-zA-Z]:匹配一个字母 \K:重置匹配信息 \d+:匹配1+个数字 您可以使用preg_match_all在php中使用此正则表达式:

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

正则表达式详细信息:

?:确保我们在当前职位之前没有收到信函 [a-zA-Z]:匹配一个字母 \K:重置匹配信息 \d+:匹配1+个数字
另一种变体可能用于跳过不符合条件的匹配

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

[A-Z]{2,}\d+匹配2个或更多大写字符A-Z和1+位 *跳过*失败使用跳过失败避免匹配 |或 [A-Z]\d+匹配单个字符A-Z并在组1中捕获一个或多个数字 |

这些匹配项是第一个捕获组

$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+

|

另一种变体可用于跳过不符合条件的匹配

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

[A-Z]{2,}\d+匹配2个或更多大写字符A-Z和1+位 *跳过*失败使用跳过失败避免匹配 |或 [A-Z]\d+匹配单个字符A-Z并在组1中捕获一个或多个数字 |

这些匹配项是第一个捕获组

$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+

|

非常感谢anubhava!非常好。您发布的代码中只缺少左括号。必须是这样的:preg_match_all'/?非常感谢anubhava!非常好。您发布的代码中只缺少左括号。必须是这样的:preg_match_all'/?