当前位置:首页 > 开发 > C# > 正文内容

C# 正则表达式

C#3年前 (2022-10-01)
命名空间    
using System.Text.RegularExpressions;
匹配结果唯一    
string text = "刚才最后一响,北京时间,17:00:00整。";
string pattren = @"(\d{2}):(\d{2}):(\d{2})";

if (regex.IsMatch(text))    //是否匹配
{
    Match match = Regex.Match(text, pattren);
    Console.WriteLine("匹配结果:\n\t\t{0}", match.Value);
    Console.WriteLine("子匹配项");
    GroupCollection groupCollection = match.Groups;
    for (int i = 0; i < groupCollection.Count; i++)
    {
        Console.WriteLine("\t\t" + i + "\t" + groupCollection[i].Value);
    }
}
else
{
    Console.WriteLine("null");
}
Console.Read();

控制台输出

匹配结果:
                17:00:00
子匹配项
                0       17:00:00
                1       17
                2       00
                3       00


匹配结果多项    
string text = "当前时间 17:01:02,目标时间,18:03:04。";
string pattren = @"(\d{2}):(\d{2}):(\d{2})";

if (regex.IsMatch(text))
{
    MatchCollection matchCollection = Regex.Matches(text, pattren);
    for (int i = 0; i < matchCollection.Count; i++)
    {
        GroupCollection groupCollection = matchCollection[i].Groups;
        Console.WriteLine("匹配结果{0}",i);
        for (int i2 = 0; i2 < groupCollection.Count; i2++)
        {
                    Console.WriteLine("\t\t{0}\t{1}",i2,groupCollection[i2].Value);
        }
    }
}
else
{
    Console.WriteLine("null");
}
Console.Read();

控制台输出

匹配结果0
                0       17:01:02
                1       17
                2       01
                3       02
匹配结果1
                0       18:03:04
                1       18
                2       03
                3       04




转载请注明出处。

本文链接:http://pythonopen.com/?id=215

相关文章

C# OnMeasureItem

1. **整体功能概述**   - `OnMeasureItem` 是一个在Wi...

C# ref 和out

ref关键字概念:ref是 C# 中的一个关键字,用于按引用传递参数。当在方法调用中使用ref关键字...

C# i++和++i的区别

核心区别操作顺序            ...