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

如何在C#中使用正则表达式替换所有匹配的子字符串?

嘿,这个需求用C#的Regex.Replace就能轻松搞定,我给你拆解下具体实现:

首先得明确:你提到的"foo*bar"是通配符风格的匹配规则,*代表任意字符,但在正则表达式里*是量词(匹配前面元素0次或多次),所以我们需要把这个通配符转换成对应的正则逻辑,或者直接写精准的正则表达式来实现匹配。

直接使用正则替换的核心实现

首先要引用System.Text.RegularExpressions命名空间(这是C#处理正则的核心类库)。针对你的例子,我们需要匹配以foo开头、bar结尾,中间包含任意字符的子串,这里用非贪婪匹配.*?来避免意外匹配过长的内容(比如如果字符串里有多个bar,非贪婪模式会匹配从foo到最近的那个bar)。

代码示例:

using System.Text.RegularExpressions;

// 你的输入字符串
string inputString = "foo2bar and foo2bax and fooTheQuickFax";
// 正则表达式:匹配foo开头,任意字符(非贪婪),直到bar结尾
string regexPattern = @"foo.*?bar";
// 替换后的目标字符串
string replacementText = "baz";

// 执行替换
string outputString = Regex.Replace(inputString, regexPattern, replacementText);

// 输出结果:"baz and foo2bax and fooTheQuickFax"
Console.WriteLine(outputString);

如果你想保留通配符风格的调用形式

如果你希望更贴近你描述的inputString.Replace("foo*bar", "baz")调用体验,可以写一个简单的工具方法,把通配符转换成正则表达式:

public static string WildcardToRegex(string wildcard)
{
    // 先转义正则特殊字符,再把通配符*换成正则的.*,?换成.
    return Regex.Escape(wildcard).Replace("\\*", ".*").Replace("\\?", ".");
}

// 使用方式
string pattern = WildcardToRegex("foo*bar");
string output = Regex.Replace(inputString, pattern, replacementText);

额外实用提示

  • 贪婪/非贪婪匹配:上面用的.*?是非贪婪模式,会匹配从foo到最近的bar;如果用.*(贪婪模式),遇到多个bar时会匹配从第一个foo到最后一个bar的整个长串,根据你的实际需求选择即可。
  • 大小写敏感:默认正则是区分大小写的,如果需要忽略大小写,在Regex.Replace里加上RegexOptions.IgnoreCase参数:
    string output = Regex.Replace(inputString, regexPattern, replacementText, RegexOptions.IgnoreCase);
    
  • 匹配换行符:默认.不匹配换行符,如果需要匹配包含换行的内容,加上RegexOptions.Singleline参数。

内容的提问来源于stack exchange,提问作者A X

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:27:02