当前位置:首页 > 编程语言 > C# > 正文内容

C# 正则表达式

C#2年前 (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




相关文章

C# 获取文件图标

string file = @"C:\Windows\exp...

C#解析Torrent获取磁力链

NuGet添加 MonoTorrentusing MonoTorrent;string&n...

C# ArrayList

添加的成员可以是任意类型    ArrayList arra...

C# 前++,与后++的区别

简单一句话,前++是自身先加1,再运算,后加加是先运算,然后再自身加1后++   ...

C# SHA1

GetFileSHA1        ...

C# Winform 使用控件移动窗口

前置     将窗口的FormBorderStyle属性设置为F...