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 = "快小鸟乐的";则返回"快小鸟乐"

  • 相关阅读:
    Docker网络简介
    Dockerfile数据管理
    Dockerfile指令详解下
    Dockerfile指令详解上
    设计模式之装饰器模式
    设计模式之适配器模式
    Java NIO的工作方式
    使用Dockerfile定制镜像
    jquery+asp.net 调用百度geocoder手机浏览器定位--Api介绍及Html定位方法
    js 取父级 页面上的元素
  • 原文地址:https://www.cnblogs.com/paulhe/p/3940853.html
Copyright © 2011-2022 走看看