我有一个匹配英国邮编第一部分的正则表达式:
/^[A-Z]{1,2}[0-9]{1,2}$/
但是我想允许这个的倍数,所以需要检查如下条目:
BT5,BT6,BT9, BT43, BT21
即由逗号或逗号加空格分隔的多个条目。
我添加什么到我的正则表达式来实现这一点?
我假设前面或后面的逗号是不允许的,并且需要至少有一个条目。这给你:
/^'s*[A-Z]{1,2}[0-9]{1,2}(?:'s*,'s*[A-Z]{1,2}[0-9]{1,2})*'s*$/
在regex101.com上进行实时测试。
解释:
^ # Start of string
's* # Match optional whitespace
[A-Z]{1,2}[0-9]{1,2} # Match one postcode
(?: # Start of (repeated) noncapturing group:
's*,'s* # Match a comma, optionally surrounded by whitespace
[A-Z]{1,2}[0-9]{1,2} # Match one postcode
)* # Repeat as needed (including zero times)
's* # Match optional whitespace
$ # End of string
像这样展开它(参见regex演示):
^[A-Z]{1,2}[0-9]{1,2}(?:, ?[A-Z]{1,2}[0-9]{1,2})*$
- 在第一个邮政编码之后,非捕获组
(?:, ?[A-Z]{1,2}[0-9]{1,2})*
匹配零次或多次… -
, ?
逗号加可选空格… - 和另一个邮政编码
[A-Z]{1,2}[0-9]{1,2}
$regex = '~^[A-Z]{1,2}[0-9]{1,2}(?:, ?[A-Z]{1,2}[0-9]{1,2})*$~';
if (preg_match($regex, $yourstring, $m)) {
$thematch = $m[0];
}
else { // no match...
}
你可以实现这样一个正则表达式:
/[A-Z]{1,2}[0-9]{1,2}/
那么你可以使用:
preg_match_all("/[A-Z]{1,2}[0-9]{1,2}/", "BT5,BT6,BT9, BT43, BT21", $matches);
检索包含所有匹配项的数组。
如果你想要一个正则表达式只接受邮政编码之间带有一些"噪音"的字符串,你可以尝试:
/^([A-Z]{1,2}[0-9]{1,2})(, ?([A-Z]{1,2}[0-9]{1,2}))*$/
对于[ ,]
,中间允许的字符列表(如空格和逗号)