【问题标题】:How to Replace by pattern with Regex in C#如何在 C# 中用正则表达式替换模式
【发布时间】:2017-10-24 07:20:42
【问题描述】:

我有一个文本,该文本包含以 # 开头并以 ="" 字符结尾的字符序列。 # 和 ="" 字符之间只存在字母数字字符,没有空格或 ;字符。 我试图找到具有以下模式的指定序列#[A-Za-z0-9]+(="") 我的问题是如何用三个问号字符替换 ="" 字符???在 C# 中?

提前谢谢你。

【问题讨论】:

    标签: c# regex replace pattern-matching


    【解决方案1】:

    做你需要的正确方法是捕获你需要保留的部分,只匹配你需要替换的部分:

    var result = Regex.Replace(s, "(#[A-Za-z0-9]+)=\"\"", "$1???");
    

    请参阅regex demo

    (#[A-Za-z0-9]+)="" 模式中,# 和字母数字字符被捕获到第 1 组,然后在替换反向引用 $1(也称为第 1 组的占位符)的帮助下重新插入到结果字符串中)。由于="" 是一个已知长度的字符串,您可以安全地在$1 之后放置三个? 字符。

    如果你无法控制模式,只需要替换第一组的内容,并且如果你不知道第二组值的长度(不是这样,但让我们概括一下),你可以考虑以下方法:

    var s = "#Abc=\"\"";
    var result = Regex.Replace(s, "#[A-Za-z0-9]+(=\"\")", m=> 
        string.Format("{0}{1}{2}", 
           m.Value.Substring(0, m.Groups[1].Index), // Get the substring up to Group 1 value
           new string('?', m.Groups[1].Length), // Build the string of Group 1 length ?s
           m.Value.Substring(m.Groups[1].Index+m.Groups[1].Length,  m.Value.Length-m.Groups[1].Index-m.Groups[1].Length))); // Append the rest of the match
    Console.WriteLine(result);
    

    this C# demo

    【讨论】:

      猜你喜欢
      • 2012-02-12
      • 1970-01-01
      • 1970-01-01
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多