c#

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

小亿
399
2023-08-01 20:14:03
栏目: 编程语言

使用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

0
看了该问题的人还看了