You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#正则表达式仅替换首个匹配项,如何实现全行所有匹配替换?

问题原因

你的正则模式@"^test[0-9a-zA-Z]+"里的^是行首锚定符,它只会匹配每行开头位置符合test[0-9a-zA-Z]+规则的字符串。当替换掉行首的匹配项后,后续的匹配项不在行首位置,就无法被^锚定匹配到,导致只能替换每行的首个匹配项。

另外,你嵌套的while(Regex.IsMatch(line, ma) != false)循环完全没必要,Regex.Replace默认就会替换目标字符串中的所有匹配项,不需要手动循环检测。

修正方案
  1. 移除正则中的^锚点,让模式可以匹配行内任意位置的test开头字符串;
  2. 简化代码,直接用Regex.Replace一次性替换每行的所有匹配项,无需嵌套循环。

修正后的代码如下:

using System.Text.RegularExpressions;
string filePath = "test.txt";
string fileNewPath = "test1.txt";

// 移除^锚点,匹配任意位置的test开头字符串
string ma = @"test[0-9a-zA-Z]+";

string newString = string.Empty;
using(StreamReader sr = new(filePath)){
    string line = sr.ReadLine();

    while (line != null){
        // 直接替换当前行所有匹配项,无需循环
        line = Regex.Replace(line, ma, "");
        newString += line + "\n";
        line = sr.ReadLine();
    }
}
using(StreamWriter sw = new(fileNewPath)){
    sw.WriteLine(newString);
}
效果验证

原文本内容:

testebook kok o testebook
testbbb1232 joj  ds testbbb1232

替换后输出:

kok o 
 joj  ds 

内容的提问来源于stack exchange,提问作者Beka Tchigladze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 04:20:27