Regular expressions: how to match numbers?

谁都会走 提交于 2020-01-25 07:12:06

问题


I want to use regular expressions to match numbers like these:

58158
60360
98198

That is in the format ABCAB.

I use code below to match ABAB:

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

such as 5858 but how to match ABCAB(58158)?


回答1:


For numbers in the format ABCAB:

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

This places no restriction on A=B=C. Use negative look-ahead for A!=B!=C:

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

Edit:

There is no boundary matching so 58158 will be matched in 36958158:

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

>>> 58158



回答2:


To match integers in the form ABCAB, use \b(\d\d)\d(\1)\b.

\b is a word boundary and \1 references the first group.

Example (in JavaScript so that it can be tested in the browser but it works in most regex solutions) :

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

gives

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


来源:https://stackoverflow.com/questions/15346178/regular-expressions-how-to-match-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!