问题
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