<?php
$string = '395095427174400_558374047513203';
if(preg_match("/^[0-9][_][0-9]$/",$string)){
echo "True";
}else{
echo "False";
}
?>
为什么我的正则表达式在数字之间不匹配和下划线?正则表达式之间的下划线
<?php
$string = '395095427174400_558374047513203';
if(preg_match("/^[0-9][_][0-9]$/",$string)){
echo "True";
}else{
echo "False";
}
?>
为什么我的正则表达式在数字之间不匹配和下划线?正则表达式之间的下划线
您需要使用quantifier
才能在underscore
之前匹配更多数量的digits
。而且您并不需要将underscore
设置为character class
。
你可以试试这个正则表达式: -
/^[0-9]+_[0-9]+$/
你regex
不匹配的数字之间的下划线,只是单个数字即是。
/^[0-9][_][0-9]$/
^ # Start of line
[0-9] # A single digit
[_] # An underscore
[0-9] # A single digit
$ # End of line
你想用+
匹配一个或多个数字:
^ # Start of line
[0-9]+ # One or more digit
_ # An underscore
[0-9]+ # One or more digit
$ # End of line
在你的模式^
和$
限制正则表达式引擎整场比赛字符串,你有附近的多个数字所以你的模式失败。添加具有[0-9]
一个+
可以解决这个问题,因为其他专家(一个或多个)建议是这样的:
/^[0-9]+_[0-9]+$/
而且,我不建议用数字工作时使用的字符类,正则表达式引擎支持\d
用于这一目的。
简化你的模式是这样的:
/^\d+_\d+$/
另外,如果你是相当肯定的下划线只能位数(S)(未开始和结束)之间发生的,你甚至可以更简化它像此:
/^_|\d+$/