【问题标题】:How to replace a matched regex expression with another string in C#如何用 C# 中的另一个字符串替换匹配的正则表达式
【发布时间】:2018-03-17 18:32:11
【问题描述】:

我想用 C# 中的另一个字符串替换与正则表达式匹配的所有子字符串实例。例如,函数调用可能如下所示:

inputString.Replace("foo*bar", "baz");

如果输入字符串是(仅示例):

"foo2bar and foo2bax and fooTheQuickFax"

输出将是(仅示例):

"baz and foo2bax and fooTheQuickFax"

有谁知道如何实现这个结果?

注意:这个问题不是重复的。这是专门询问Regex,并举了一个例子。它不是询问如何在两个字符串之间找到字符串 - 将其标记为重复的人没有阅读问题。

【问题讨论】:

    标签: c# .net regex string


    【解决方案1】:
    Regex.Replace("foo2bar and foo2bax and fooTheQuickFax", "foo.*bar", "baz");
    

    【讨论】:

      【解决方案2】:

      使用Regex.Replace()方法类似

        string pattern = "\\foo?bar";
        string replacement = "baz";
        Regex rgx = new Regex(pattern);
        string result = rgx.Replace(input, replacement);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-11-30
        • 1970-01-01
        • 2012-01-25
        • 2021-09-17
        • 1970-01-01
        • 1970-01-01
        • 2011-09-02
        相关资源
        最近更新 更多