[英]Regex & Phone Numbers
So I have been working on creating a regex to validate phone numbers in the following format XXX-XXX-XXXX which has been working pretty well so far, but now I'm trying to figure out how to remove the ability to enter specific numbers like "123-456-7890".所以我一直在努力创建一个正则表达式来验证以下格式的电话号码 XXX-XXX-XXXX 到目前为止效果很好,但现在我想弄清楚如何删除输入特定数字的能力,比如“123-456-7890”。
My current regex is我目前的正则表达式是
(^[0-9]{3}-[0-9]{3}-[0-9]{4}$)
I've been looking into it for a few days, but I can't seem to figure out what to add to my current expression in order to get "any number with formats XXX-XXX-XXXX BUT NOT 123-456-7890"我已经研究了几天,但我似乎无法弄清楚要在我当前的表达式中添加什么以获得“格式为 XXX-XXX-XXXX 但不是 123-456-7890 的任何数字”
Can anyone help me with this?谁能帮我这个?
Thank you so much太感谢了
If negative look-ahead is supported in whatever version you're running, this should work:如果您正在运行的任何版本都支持负面前瞻,那么这应该有效:
(^(?!123-456-7890)[0-9]{3}-[0-9]{3}-[0-9]{4}$)
It's the same expression you used, just with a negative look-ahead added in the beginning.它与您使用的表达式相同,只是在开头添加了否定的前瞻性。
(?!123-456-7890)
checks if the character sequence ahead doesn't match the pattern '123-456-7890'. (?!123-456-7890)
检查前面的字符序列是否与模式“123-456-7890”不匹配。
Only if this condition is met, the rest of the pattern will be considered.只有满足此条件,才会考虑模式的 rest。
The same can be done by checking after matching the pattern using the look-behind expression (?<!123-456-7890)
同样可以通过使用后视表达式(?<!123-456-7890)
在匹配模式后进行检查来完成
(^[0-9]{3}-[0-9]{3}-[0-9]{4}(?<!123-456-7890)$)
in case that's faster or more practical for you.如果这对您来说更快或更实用。
https://regex101.com/r/GOyOgf/1 https://regex101.com/r/GOyOgf/1
I would break them into 2 regexes for simplicity and you can use an alternation for the not matches, like this:为简单起见,我会将它们分成 2 个正则表达式,您可以对不匹配项使用交替,如下所示:
var regexToMatch = new Regex("(^[0-9]{3}-[0-9]{3}-[0-9]{4}$)");
var regexToNotMatch = new Regex("(123-456-7890)|(098-765-4321)");
var testString = "123-456-7890";
if(regexToMatch.IsMatch(testString) && !regexToNotMatch.IsMatch(testString))
{
Console.WriteLine("Valid!");
}
else
{
Console.WriteLine("Not Valid!");
}
And here's a working fiddle of it.这是它的工作小提琴。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.