zoukankan      html  css  js  c++  java
  • C#中正则表达式的简单使用

    C#中有关正则表达式的类包含在System.Text.RegularExpressions命名空间中,可通过一下代码添加该命名空间:

    1 using System.Text.RegularExpressions;
    View Code

    字符串匹配中,主角是"被匹配串"和"匹配模式"。

     1 // 定义 "被匹配串"
     2 string message = " mother father sister brother ";
     3 // 定义 "匹配模式"
     4 string pattern = @"(w+)ther";
     5 // 用静态方法进行匹配,也可以通过创建正则对象进行匹配
     6 MatchCollection matches = Regex.Matches(message, pattern);
     7 // 遍历得到的结果
     8 foreach (Match match in matches) {
     9     Console.WriteLine("Groups[0].Value = {0} --- Groups[1].Value = {1}", match.Groups[0].Value, matchGroups[1].Value); 
    10 } 
    11 
    12 // 输出
    13 // Groups[0].Value = mother --- Groups[1].Value = mo
    14 // Groups[0].Value = father --- Groups[1].Value = fa
    15 // Groups[0].Value = brother --- Groups[1].Value = bro
    16 // 结束输出

    这是其中一个示例,匹配方法有三种: IsMatch(), Match(), Matches().

    如果只是想知道"被匹配串"中是否包含某种"匹配模式", 可以使用IsMatch();

    如果想得到一个匹配到的结果,可以使用Match();

    如果想得到多个匹配到的结果,可以使用Matches();

    单个匹配到的结果可以使用Groups[]获取利用"匹配模式"匹配的分组,以便对匹配得到的信息的利用。

    具体使用规则:http://www.dotnetperls.com/regex-match

  • 相关阅读:
    Spring boot 梳理
    Spring boot 梳理
    Spring boot 梳理
    观察者模式
    设计模式原则
    Spring MVC上传文件
    Spring MVC视图解析器
    Spring MVC中Action使用总结
    Spring MVC控制器
    Java并发 两个线程交替执行和死锁
  • 原文地址:https://www.cnblogs.com/mchcylh/p/4302004.html
Copyright © 2011-2022 走看看