当前位置:首页 > 开发 > 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://www.pythonopen.com/?id=215

相关文章

C# 数据类型

Type ByteLenghtMinMax.NET Framework Typedefau...

C# 结构体struct 例子

/// <summary> /// 结构体 /// &...

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

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

C# 获取屏幕高宽度

方式1-不包含任务栏高度    var primaryScr...

在 C# 中实现类似于 Windows 资源管理器的“名称”排序方式

要在 C# 中实现类似于 Windows 资源管理器的“名称”排序方式,你需要考虑以下几点:1. 不...

C# 类接口

定义接口是一种抽象类型,它定义了一组方法签名(方法名称、参数列表和返回类型),但没有方法体。接口用于...