简体   繁体   English

正则表达式,用于使用CSV将字符串格式验证为特定长度

[英]Regular expression to validate string format to specific length with csv

I am trying to write a regular expression which validates a text box to have only digits with length 5 or 9. I found the below regular expression to get this done 我正在尝试编写一个正则表达式来验证文本框是否只有长度为5或9的数字。我找到了以下正则表达式来完成此操作

^\d{1,5}([,]\d{5})*$

but it could not fix my requirement correctly, Can any one please help me in modifying or writing a new regular expression which supports below pattern. 但是它不能正确地满足我的要求,任何人都可以帮助我修改或编写支持以下模式的新正则表达式。

  • 09103,09101, valid (ending with comma) 09103,09101, 有效 (以逗号结尾)
  • 09103,09101 valid (not ending with comma) 09103,09101 有效 (不以逗号结尾)
  • 12345,1234567 Invalid (should not support if 1st digit is length 5 and 2nd less than 9) 12345,1234567 无效 (如果第一个数字的长度为5而第二个数字的长度小于9,则不支持)
  • 12345,123456789 valid (must support only digit length 5 or 9) 12345,123456789 有效 (必须仅支持数字长度5或9)

Please try the following: 请尝试以下操作:

var lines = new []
{
    "09103,09101,",
    "09103,09101",
    "12345,1234567",
    "12345,123456789",
    "12345"
};

var re = new Regex(@"^\d{1,5}(,(\d{5}|\d{9}))?,?$");

foreach (var line in lines)
{
    Console.WriteLine("{0} = {1}", line, re.IsMatch(line) ? "Valid" : "Invalid");
}

Output 产量

09103,09101, = Valid
09103,09101 = Valid
12345,1234567 = Invalid
12345,123456789 = Valid
12345 = Valid

You can run it here: C# Fiddle 您可以在此处运行它: C#小提琴

Try this, for your exact test cases. 尝试一下,以获取确切的测试用例。

^\d{5},?$|^\d{5},\d{5},?$|^\d{5},\d{9},?$

It uses the | 它使用| character to separate 'alternative' patterns, read it as "or". 字符以分隔“替代”模式,将其读取为“或”。 Ie

^\d{5}$  OR  ^\d{5},\d{5}$  OR  ^\d{5},\d{9}$

Just make the part which was preceded by comma to optional, so that it would match only 12345 or 12345, 只需将逗号前的部分设为可选,这样它就只能匹配1234512345,

^(?:\d{5}|\d{9})(?:,(?:\d{5}|\d{9}))?,?$

DEMO DEMO

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

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