[英]Regex of phone number - how to make sure the user won't put +-*+-*+-*+-*?
I want to allow the user to enter only patterns like: 我想允许用户仅输入以下模式:
+9720545455454
+9720545455454
056565656345
056565656345
03-43434344
03-43434344
0546-4234234
0546-4234234
*9090
* 9090
+97203-0656534
+ 97203-0656534
Meaning, I don't want to allow the user to gibberish everything together, like: 意思是,我不想让用户将所有内容混为一谈,例如:
+954-4343+3232*4343+-
+ 954-4343 + 3232 * 4343 +-
+-4343-+5454+9323+234
+ -4343- + 5454 + 9323 + 234
How can I fixed this pattern 我该如何解决这个问题
public static bool IsPhoneNumberCorrect(string phoneNumber)
{
return Regex.IsMatch(phoneNumber, @"^[0-9*+-]+$");
}
for that purpose? 为了这个目的?
If you do not care about digit group length, you can allow +
or *
only at the beginning, and then match initial digits and then optional groups of hyphen+digits: 如果您不关心数字组的长度,则可以只在开头允许
+
或*
,然后匹配初始数字,然后匹配连字符+数字的可选组:
return Regex.IsMatch(phoneNumber, @"^[+*]?\d+(?:-\d+)*$");
Note you can limit the number of hyphen+digit with a quantifier. 请注意,您可以使用量词限制连字符+数字的数量。 Say, there can be none or 1:
说,不能有一个或一个:
^[+*]?\d+(?:-\d+)?$"
^
See another demo 观看另一个演示
And in case there can be more than 1, use a limiting quantifier: 如果可以超过1,请使用限制量词:
^[+*]?\d+(?:-\d+){0,3}$"
^^^^^
Here, {0,3}
means 0, 1, 2 or 3 repetitions of the hyphen+digits group. 此处,
{0,3}
表示连字符+数字组的0、1、2或3个重复。
^(?!(.*\+){2})(?!(.*-){2})(?!(.*\*){2})[0-9*+-]+$
YOu can use lookaheads
to make sure special characters
appear only once
.See demo. 您可以
lookaheads
使用以确保special characters
仅出现once
参阅演示。
https://regex101.com/r/vV1wW6/1 https://regex101.com/r/vV1wW6/1
What you first need to do is identify what exactly the pattern is. 您首先需要做的就是确定模式到底是什么。 This doesn't need to be in code.
不需要在代码中。 In you example, I see a leading character, followed by a first number group, followed by an optional dash and second number group.
在您的示例中,我看到一个前导字符,后跟第一个数字组,然后是可选的破折号和第二个数字组。 The leading character can be +, * or 0. The number groups are one digit between 1 and 9 followed by one or more digits 0 to 9. Translating each element gives:
前导字符可以是+,*或0。数字组是1到9之间的一位数字,后跟一个或多个0到9数字。转换每个元素将得到:
Leader: [+*0] 组长:[+ * 0]
Dash: - 破折号:-
Number group: [1-9][0-9]+ 号码组:[1-9] [0-9] +
Throwing everything together you get 把所有东西都扔在一起
[\+\*0][1-9][0-9]+(-[1-9][0-9]+)?
Some groups may have minimum and maximum lengths, you can still work that in changing + to {min, max}. 某些组可能具有最小和最大长度,您仍然可以将+更改为{min,max}。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.