[英]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.