简体   繁体   English

正则表达式:如何匹配数字?

[英]Regular expressions: how to match numbers?

I want to use regular expressions to match numbers like these: 我想使用正则表达式来匹配这样的数字:

58158
60360
98198

That is in the format ABCAB . 格式为ABCAB

I use code below to match ABAB : 我使用下面的代码来匹配ABAB

(([\d]){1,}([\d]){1,})\1{1,}

such as 5858 but how to match ABCAB(58158)? 例如5858但如何搭配ABCAB(58158)?

For numbers in the format ABCAB : 对于ABCAB格式的ABCAB

(\d)(\d)\d\1\2

This places no restriction on A=B=C . 这对A=B=C没有限制。 Use negative look-ahead for A!=B!=C : A!=B!=C使用否定的前瞻

(\d)(?!\1)(\d)(?!\1|\2)\d\1\2

Edit: 编辑:

There is no boundary matching so 58158 will be matched in 36958158 : 没有边界匹配,因此58158将在36958158匹配:

$num=36958158;
preg_match('/(\d)(?!\1)(\d)(?!\1|\2)\d\1\2/',$num,$match);
echo ">>> ".$match[0];

>>> 58158

To match integers in the form ABCAB, use \\b(\\d\\d)\\d(\\1)\\b . 要匹配ABCAB形式的整数,请使用\\b(\\d\\d)\\d(\\1)\\b

\\b is a word boundary and \\1 references the first group. \\b是单词边界, \\1引用第一组。

Example (in JavaScript so that it can be tested in the browser but it works in most regex solutions) : 示例(使用JavaScript,以便可以在浏览器中对其进行测试,但可以在大多数正则表达式解决方案中使用):

var matches = '58158 22223 60360 98198 12345'.match(/\b(\d\d)\d(\1)\b/g);

gives

["58158", "60360", "98198"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM