2

我正在尝试验证遵循下一个模式的电话号码

01\d{9} 
2\d{7}

但是用户可以输入多个以空格分隔的数字或在一个输入字段中输入所以我想出了正则表达式

/(?:(?:01\d{9}$)|(?:2\d{7}$) ){1,}
A Test Sample
"01226113130 26322612 24586154 01004598654"

我的表情与此示例不匹配,有什么帮助吗?

解决方案 对于其他人,如果他们在问题上失败,您可以尝试 Jerry Solution 或这个

(?:(?:(?:01\d{9}(?:[\- \,])*)|(?:2\d{7}[\- \,]*))){1,}
4

1 回答 1

2

Try this one:

^(?:(?:01\d{9}|2\d{7}) ){1,}(?:01\d{9}|2\d{7})$

Your current regex has (?:01\d{9}$)|(?:2\d{7}$) where the $ forced it to 'prematurely end' the match, so removing this was the first thing to do. Then (?:01\d{9})|(?:2\d{7}) can be re-written as (?:01\d{9}|2\d{7}). I added a ^ for the beginning of the string.

Afterwards, this regex will only validate strings ending with a space, so add another (?:01\d{9}|2\d{7}) at the end and finally conclude with $.

regex101 demo.

Oh, also, it might be better to turn the {1,} into * like this:

^(?:(?:01\d{9}|2\d{7}) )*(?:01\d{9}|2\d{7})$
于 2013-09-01T19:20:18.633 回答