使用C#正则表达式提取文本内容的步骤如下:
-
引入
System.Text.RegularExpressions
命名空间。 -
创建一个正则表达式模式。
-
使用
Regex.Match
方法匹配文本内容。 -
使用
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