用正则验证字符串格式,形如:A)XXX B)XXXX C)XXX

时间:2024-08-10 10:04:50

今天遇到个小功能,要验证某个英文选项是否正确,例如: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

想了想,还是用正则先分成一个字符串数组,每个元素即每个单选项,所以就顺手写了下,发现很简单也蛮有趣的:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions; namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Check(@"A)accumulate B)circling C)communities D)competition E)domestic
F)financially G)formally H)gather I)households J)recession "));
Console.WriteLine(Check(@"A|accumulate B)circling C)communities D)competition"));
Console.WriteLine(Check(@"A)accumulate C)communities D)competition"));
Console.WriteLine(Check(@"A|accumulate"));
Console.WriteLine(Check(@"")); Console.Read(); //输出结果
//true
//false
//false
//false
//false
} public static bool Check(string options)
{
MatchCollection mc = Regex.Matches(options,@"[A-Z]\)[^A-Z]*"); //匹配A)XXX,直到下一个A)
//没匹配到,直接返回false
if (mc.Count == )
{
return false;
}
//匹配到,继续检验
else
{
char c = 'A';
string bracket = ")";
foreach (Match option in mc)
{
//形如A)
string tmp = c + bracket;
if (!option.Value.Contains(tmp))
return false;
//A自增为B
c++;
}
return true;
} }
}
}
务必引用c#的正则库函数:  using System.Text.RegularExpressions;