今天遇到个小功能,要验证某个英文选项是否正确,例如:A)accumulate B)circling C)communities D)competition E)domestic F)financially G)formally H)gather I)households J)recession K)reported L)reviewed M)serves N)surrounding O)survive
要求:1.必须按顺序排下来,ABCD....
2.选项后代英文)
符合格式则返回true,不符合则为false
想了想,还是用正则先分成一个字符串数组,每个元素即每个单选项,所以就顺手写了下,发现很简单也蛮有趣的:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Text.RegularExpressions; 6 7 namespace ConsoleApplication1 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 Console.WriteLine(Check(@"A)accumulate B)circling C)communities D)competition E)domestic 14 F)financially G)formally H)gather I)households J)recession ")); 15 Console.WriteLine(Check(@"A|accumulate B)circling C)communities D)competition")); 16 Console.WriteLine(Check(@"A)accumulate C)communities D)competition")); 17 Console.WriteLine(Check(@"A|accumulate")); 18 Console.WriteLine(Check(@"")); 19 20 Console.Read(); 21 22 //输出结果 23 //true 24 //false 25 //false 26 //false 27 //false 28 } 29 30 public static bool Check(string options) 31 { 32 MatchCollection mc = Regex.Matches(options,@"[A-Z])[^A-Z]*"); //匹配A)XXX,直到下一个A) 33 //没匹配到,直接返回false 34 if (mc.Count == 0) 35 { 36 return false; 37 } 38 //匹配到,继续检验 39 else 40 { 41 char c = 'A'; 42 string bracket = ")"; 43 foreach (Match option in mc) 44 { 45 //形如A) 46 string tmp = c + bracket; 47 if (!option.Value.Contains(tmp)) 48 return false; 49 //A自增为B 50 c++; 51 } 52 return true; 53 } 54 55 } 56 } 57 }
务必引用c#的正则库函数: using System.Text.RegularExpressions;