zoukankan      html  css  js  c++  java
  • 用正则验证字符串格式,形如:A)XXX B)XXXX C)XXX

    今天遇到个小功能,要验证某个英文选项是否正确,例如: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;
  • 相关阅读:
    文档管理项目
    根据商品名称、价格区间检索商品的SQL语句
    ASP.NET MVC进阶三
    ASP.NET MVC进阶二
    vscode编写html,常用快捷方式与插件
    bpexpdate – 更改映像目录库中备份的截止日期以及介质目录库中介质的截止日期nbu
    Netbackup用于技术支持的问题报告(报障模版)
    netbackup 8.1安装注意事项
    金融的本质是什么?终于有人讲清楚了!(源于网络)
    nbu集群Alwayson相关问题
  • 原文地址:https://www.cnblogs.com/nlh774/p/3471933.html
Copyright © 2011-2022 走看看