zoukankan      html  css  js  c++  java
  • C# 正则表达式的用法 及 常用正则表达式

    最近一直用正则表达式提取文档中的数据,正则真是提取数据的好帮手,用好了正则,想提取什么数据就提取什么数据。

    呵呵,当然前提是数据必须有规则。正则嘛,一切在规则之上。。

    正则表达式的名字空间:

    using System.Text.RegularExpressions;

    常用用法1:

    string str =string.Empty;

    string pattern =@"(?<=No. of Failed :).*";
    Match match
    = Regex.Match(fileStream, pattern, RegexOptions.IgnoreCase);
    if (match.Success)
    {
    str
    = match.ToString().Trim();
    }

    return str;

     这短代码直接截取有多少个Failed。

    常用用法2:

    // Match the Version
    string pattern =@"(?<=Generator )(\d+\.){0,3}\d+";
    MatchCollection matches
    = Regex.Matches(strReportFileStream, pattern, RegexOptions.None);

    foreach (Match nextMatch in matches)
    {
    version
    = nextMatch.ToString();
    }

    匹配多个,呵呵,注意判断matches的Success.

    常用用法3:

    if (Regex.IsMatch(strSummary, @"MyPattern"))
    {
    ProcSummary(....);
    }

    不解释了。。。

     //-------------

     // 以下是常用正则,以后还会填。。

     //-------------

    1. email地址:\w+([+-.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

    解释:\w+ 必须以一个a-z,a-z,0-9_这些字符中的一个开头。([-+.]\w+)* 的意思是:允许0个或是多个-+.a-+.aa这样的字符,也就是说,到这里为止,邮件的地址可以是:a-aa+aaa.aaa这种作为开头。接下来@ 就不用解释了,邮件必须的东西。  \.匹配小数点本身,当小数点没有在[]中是,要匹配它必须进行转义。\w+意思同上。([-.]\w+)*意思是允许出现0个或是多个 -.加一个字符或是多个字符的情况。\.意思就是.就像\\就是指\一样。\w+([-.]\w+)*意思和上面的一样。

    2. 截取字符串,去掉括号里面的内容。

    var input = "User Name (email@address.com)";

    var output = Regex.Replace(input, @" ?\(.*?\)", string.Empty);

  • 相关阅读:
    抽象工厂模式
    工厂方法模式
    简单工厂模式
    Zuul
    Turbine
    Hystrix
    Feign
    Ribbon
    Eureka
    @MappedSuperclass的作用
  • 原文地址:https://www.cnblogs.com/mantian/p/1979840.html
Copyright © 2011-2022 走看看