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

  • 相关阅读:
    Win7下用IIS发布网站
    进程的端口被占用的解决方案
    JS event loop
    慕课网
    angular js
    PowerDesign生成数据库
    CodeSmith 代码生成器
    微信小程序开发学习资料
    SSO 单点登录
    面试
  • 原文地址:https://www.cnblogs.com/paulhe/p/3940853.html
Copyright © 2011-2022 走看看