[英]php regex question - test 10 digits long with first 5 same digit and second 5 another
我正在嘗試將此java移植到php:
String _value = '1111122222';
if (_value.matches("(1{5}|2{5}|3{5}|4{5}|5{5}|6{5}|7{5}|8{5}|9{5}){2}")) {
// check for number with the same first 5 and last 5 digits
return true;
}
正如評論所示,我想測試一個像'1111122222'或'5555566666'的字符串
我怎么能用PHP做到這一點?
謝謝,斯科特
你可以使用preg_match
來做到這一點:
preg_match('/^(1{5}|2{5}|3{5}|4{5}|5{5}|6{5}|7{5}|8{5}|9{5}){2}$/', $_value)
如果出現錯誤,則返回匹配數(即0或1)或false 。 由於String的matches
方法僅返回true,如果整個字符串與給定模式匹配但preg_match
不匹配(子字符串足夠),則需要使用^
和$
設置字符串開頭和結尾的標記。
您也可以使用這個較短的正則表達式:
^(?:(\d)\1{4}){2}$
如果第二個數字序列需要與前者不同,請使用:
^(\d)\1{4}(?!\1)(\d)\2{4}$
好吧,你可以這樣做:
$regex = '/(\d)\1{4}(\d)\2{4}/';
if (preg_match($regex, $value)) {
return true;
}
哪個應該比你發布的正則表達式更有效(和可讀)...
或者,更短(並且可能更干凈)的正則表達式:
$regex = '/((\d)\2{4}){2}/';
$f = substr($_value, 0, 5);
$s = substr($_value, -5);
return (substr_count($f, $f[0]) == 5 && substr_count($s, $s[0]) == 5);
轉換如下。 preg_match()
是關鍵: http : //www.php.net/preg_match
$value = '1111122222';
if (preg_match('/^(1{5}|2{5}|3{5}|4{5}|5{5}|6{5}|7{5}|8{5}|9{5}){2}$/', $value)) {
// check for number with the same first 5 and last 5 digits
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.