当前位置:首页 > 开发 > 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#解析Torrent获取磁力链

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

C# double转为string并保留两位小数

在 C# 中,可以使用多种方式将 double 类型的数据转换为 string 类型并保留两位小数,...

C# BackgroundWorker的例子

以下是一个使用 BackgroundWorker 组件在 C# 中实现后台执行任务,同时在主线程更新...

C# System.IO.Path

System.IO.Path.GetExtension返回指定的路径字符串的扩展名。string&n...

C# Browsable(bool)

在编程中(比如常见的 C# 语言在开发 Windows Forms 等应用程序时),Browsabl...

C# OnMeasureItem

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