[英]Regular expression doesn't work
我需要使用php正則表達式來匹配以下模式,但不會給出預期的結果。
例如:-需要匹配模式5555 5545 9930
$id = "4567 3423 4567";
$regex = "/^[1-9]\d{4} \d{4} \d{4}$/";
if (preg_match($regex, $id)) {
// Indeed, the expression "^[2-9]\d{2} \d{3} \d{4}$" matches the date string
echo "Found a match!";
}else {
// If preg_match() returns false, then the regex does not
// match the string
echo "The regex pattern does not match. :(";
}
如果要匹配:4個非零數字+空格+ 4個數字+空格+ 4個數字
^([1-9]){4} \\d{4} \\d{4}$
應該可以解決問題
我認為修改現有正則表達式的最安全方法是在第一個[2-9]\\d{2} \\d{3}
添加一個替代項:
^(?:[2-9]\d{2} \d{3}|\d{4} \d{4}) \d{4}$
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
詳細資料 :
^
-字符串的開頭 (?:[2-9]\\d{2} \\d{3}|\\d{4} \\d{4})
-替代方法之一:
[2-9]\\d{2} \\d{3}
2
到9
數字,任意2位數字,空格和3位數字 |
- 要么 \\d{4} \\d{4}
-4位數字,空格,4位數字(對於新的字符串類型)
- 空間 \\d{4}
-4位數字 $
-字符串結尾。 參見PHP演示 :
$id = "4567 3423 4567";
$regex = "/^(?:[2-9]\d{2} \d{3}|\d{4} \d{4}) \d{4}$/";
if (preg_match($regex, $id)) {
echo "Found a match!";
} else {
echo "The regex pattern does not match. :(";
}
簡單編輯您的正則表達式將是
^[1-9]\d{3} \d{4} \d{4}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.