C# 使用正则表达式过滤文档,对结果求和
时间: 2024-10-13 15:12:20 浏览: 52
在C#中,你可以使用`System.Text.RegularExpressions`命名空间提供的正则表达式类`Regex`来进行文档内容的筛选。如果你想过滤文档并计算特定模式匹配的数字总和,可以按照以下步骤操作:
1. 首先,你需要读取文本文件的内容,可以使用`StreamReader`或`File.ReadAllText()`方法。
```csharp
string text = File.ReadAllText("yourfile.txt");
```
2. 然后,创建一个正则表达式模式,该模式应该匹配你要计算的数字。例如,如果你想要过滤出所有的整数,可以使用`\d+`作为模式。
```csharp
string pattern = @"\b\d+\b"; // 匹配一个或多个连续数字
```
3. 使用`Regex.Matches()`方法找到所有匹配项,并将它们存储在一个数组或集合中。
```csharp
MatchCollection matches = Regex.Matches(text, pattern);
```
4. 创建一个变量来保存总和,并遍历匹配项,将每个匹配到的数字转换成int类型并累加。
```csharp
int sum = 0;
foreach (Match match in matches)
{
sum += int.Parse(match.Value); // 将字符串转为int并累加
}
```
5. 最后,`sum`变量就包含了文档中符合条件的所有数字之和。
完整示例:
```csharp
using System;
using System.IO;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string text = File.ReadAllText("yourfile.txt");
string pattern = @"\b\d+\b";
MatchCollection matches = Regex.Matches(text, pattern);
int sum = 0;
foreach (Match match in matches)
{
sum += int.Parse(match.Value);
}
Console.WriteLine($"Sum of numbers in the file: {sum}");
}
}
```
阅读全文
相关推荐









