c# 正则表达式的使用
时间: 2023-06-17 22:03:34 浏览: 139
C# 中使用正则表达式需要先引用正则表达式命名空间 `System.Text.RegularExpressions`,然后使用 `Regex` 类来处理正则表达式。
以下是一个简单的例子,用于匹配一个字符串中的所有数字:
```csharp
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string input = "abc123def456ghi789";
string pattern = @"\d+";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
Console.WriteLine(match.Value);
}
}
}
```
输出结果为:
```
123
456
789
```
在这个例子中,我们使用了 `Regex.Matches()` 方法来匹配字符串中的所有数字。该方法返回一个 `MatchCollection` 类型的集合,包含了所有匹配的结果。然后我们使用 `foreach` 循环遍历这个集合,输出每个匹配结果的值。
正则表达式是一个非常强大的工具,可以用于各种场景。上述例子只是一个简单的示例,更多用法可以参考 C# 官方文档中的正则表达式部分。
阅读全文
相关推荐











