用于区分四位数的正则表达式模式

时间:2013-09-24 17:52:47

标签: c# regex

您好我有一个c#应用程序,它接受一个4位数的分机号并为其设置一个掩码。我的情况是需要根据数量应用两个不同的蒙版。

First: If the number starts with 47 or 5 return mask A.

Second: If the number starts with 6 or 55 return mask B. 

所以我以这种方式设置我的正则表达式,我不确定为什么会出错。

//Here I am trying to say, anything that start with 47 or 5 with the next 3 digits taking any number
Match first = Regex.Match(num, "^(47|(5[0123456789]{3}))");

//anything that start with 6 or 55 with the next 2 digits taking numbers 0-5
Match secong = Regex.Match(num, "(6|55[123450]{2})");

如果我使用输入num = 5850或num = 5511的上述情况,两者都是如此,但5850应该使用Mask A而5511应该使用Mask B

我该如何解决这个问题?

谢谢!

4 个答案:

答案 0 :(得分:2)

考虑以下内容......

Match first = Regex.Match(num, "^(47[0-9]{2}|5[0-9-[5]]{1}[0-9]{2})");

Match second = Regex.Match(num, "^(6[0-9]{3}|55[0-9]{2})");

答案 1 :(得分:1)

这些应该为你做。

这匹配以47或5开头的任何4位数字,不包括5作为第二位数字。

^(47|5([0-4]|[6-9]))\d{2}$

这匹配以6或55开头的任何4位数字。

^(6\d|55)\d{2}$

答案 2 :(得分:1)

我认为这会涵盖你。请注意,您可以使用\ d表示0-9,范围为0-5,然后将边界指示符(^)从第二个指示符上移开。注意我没有使用范围或\ d用于第一部分的第一部分,因为您不想匹配55.请注意分组。

//anything that start with 47 or 5 with the next 3 digits taking any number (but not 55!)
Match first = Regex.Match(num, "^((47|5[012346789])\d{2})");

//anything that start with 6 or 55 with the next 2 digits taking numbers 0-5
Match secong = Regex.Match(num, "^((6|55)[0-5]{2})");

答案 3 :(得分:0)

看起来你应该使用4个正则表达式

/^47\d{3}/

/^5\d{4}/

/^6\d{4}/

/^55\d{3}/

请注意以55开头的数字如何与您的两种情况相匹配,但反之则不适用于以5开头的数字,您应该使用该事实来区分它们< / p>


如果你想组合正则表达式,那就好了

/(^47\d{3})|(^5\d{4})/

注意:您可能还想使用输入锚点的结尾:$或字边界或负前瞻来匹配输出的结尾。