<?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+$/