Linux 拨号vps windows公众号手机端

怎么使用c#正则表达式提取文本内容

lewis 6年前 (2019-01-11) 阅读数 8 #程序编程
文章标签 c#

使用C#正则表达式提取文本内容的步骤如下:

  1. 引入System.Text.RegularExpressions命名空间。

  2. 创建一个正则表达式模式。

  3. 使用Regex.Match方法匹配文本内容。

  4. 使用Match.Groups属性获取匹配的结果。

以下是一个示例代码,提取文本中的所有邮箱地址:

using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string text = "联系我:test1@example.com, test2@example.com, test3@example.com";
string pattern = @"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b";
MatchCollection matches = Regex.Matches(text, pattern);
foreach (Match match in matches)
{
Console.WriteLine(match.Value);
}
}
}

在上面的代码中,我们使用了正则表达式模式@"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"来匹配邮箱地址。然后使用Regex.Matches方法来获取所有匹配的结果,并通过Match.Value属性获取匹配的文本内容。输出结果如下:

test1@example.com
test2@example.com
test3@example.com
版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门