zoukankan      html  css  js  c++  java
  • 使用c#正则验证关键字并找出匹配项

    在.net里,使用类Regex可以正则验证一些关键字并取出匹配项。

    1.使用Regex.IsMatch(string  input,  string  pattern,  RegexOptions  options)匹配输入字符串与指定的正则表达式是否符合条件;

    返回类型:bool  true——满足匹配条件  false——不满足匹配条件

    input:string类型,输入项

    pattern:string类型,指定的正则表达式

    options:可选,枚举值,设置正则表达式选项

    例:验证字符串中是否有“快乐”二字

    private bool CheckWords()
    {
         string strContent = "快乐的小鸟";
         string regex = "酸|快乐|快.+乐|甜";
         return Regex.IsMatch(strContent, regex, RegexOptions.IgnoreCase);//返回ture
    }

    2.使用Regex.Matches(string  input,  string  pattern,  RegexOptions  options)取出符合正则表达式条件的匹配项;

    返回类型:MatchCollection集合

    参数同IsMatch一致

    例:正则匹配成功后,取出对应匹配项

     public string GetMatchWord()
     {
          string strContent = "快乐的小鸟";
          string regex = "酸|快乐|快.+乐|甜";
          MatchCollection result = Regex.Matches(strContent, regex);
          return result.Count > 0 ? result[0].Value : string.Empty;//返回“快乐”
     }

    注:如果strContent = "快小鸟乐的";则返回"快小鸟乐"

  • 相关阅读:
    flask的Request对象
    Spinner实现列表下拉功能
    ListView用法
    DatePickerDialog和TimePickerDialog(基于对话框显示时间和日期)
    DataPicker以及TimePicker显示时间和日期(屏幕上显示)
    Floyd-Warshall算法(最短路)
    Bellman-Ford算法(最短路)
    前向星
    css3变形与动画
    CSS3背景 background-size
  • 原文地址:https://www.cnblogs.com/paulhe/p/3940853.html
Copyright © 2011-2022 走看看