简体   繁体   English

用于验证电话的正则表达式

[英]Regular expression for validating phone

I need to validate textbox for validating phone number in C# allowing only hyphens(-) and integer values. 我需要验证文本框,以验证C#中仅允许使用连字符(-)和整数值的电话号码。

I want a regular expression which allows only those. 我想要一个只允许那些的正则表达式。

Thanks in advance 提前致谢

Try the following one: 请尝试以下方法:

"^[0-9]+(-[0-9]+)*$"

It allows for numbers interspersed with hyphens, but not double hyphens, so "3-4" is correct, but "23--5" isn't. 它允许使用点号连字符,但不能使用双连字符,因此“ 3-4”是正确的,但“ 23--5”不是。

Assuming you validate in C#: 假设您在C#中验证:

var regex = new Regex(@"^(?:[0-9]+(?:-[0-9])?)*$");

However, I would also accept country codes (you need plus prefix) and spaces. 但是,我也接受国家代码(需要加前缀)和空格。 The spaces should be accepted because user may enter them and they are easy to strip from the string when it is stored into database. 应该接受空格,因为用户可以输入空格,并且在将字符串存储到数据库中时很容易从字符串中删除空格。 When the string is shown to the user it should be reformatted to have some spaces. 当向用户显示字符串时,应将其重新格式化为具有一些空格。

EDIT: I liked markijbema's version that does not accept double hyphens so I changed this to have similar matching. 编辑:我喜欢不接受双连字符的markijbema版本,因此我将其更改为具有类似的匹配项。

C#.net have it's own expression editor C#.net拥有自己的表达式编辑器

here is an example "(((\\d{3}) ?)|(\\d{3}-))?\\d{3}-\\d{4}" 这是一个示例“((((\\ d {3})?)|(\\ d {3}-))?\\ d {3}-\\ d {4}”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM