【问题标题】:Simplest way to construct a string by interpolating values into a Regex pattern?通过将值插入正则表达式模式来构造字符串的最简单方法?
【发布时间】:2011-09-08 00:24:21
【问题描述】:

我通常会遇到很多条件和/或循环来解析正则表达式并将值插回其捕获组,并且我正在寻找有经验的答案以希望以一种简单的方式解决这个问题。

例如,给定一个正则表达式模式,如X(?<xid>\d+)-(?<xsub>\w+)\.xml,具有命名的捕获组“xid”和“xsub”,旨在匹配以下文件名: X1-foo.xmlX555-bar.xml 等,当提供参数时:int xid=999, string xsub="baz",我想将这些值插入到模式组中以构造正确的文件名:X999-baz.xml

为了简单起见,显式捕获没有嵌套。


没有 String.Format

这个概念很容易通过 .NET 字符串格式项目(如String.Format("X{0}-{1}.xml", xid, xsub))来实现,但是我已经有一个正则表达式模式可以从任何文件名字符串中解析出这些值,并且希望使用相同的模式通过重构来朝相反的方向前进一个文件名,以确保准确性。如果我需要正则表达式模式来解析字符串中的值,但需要使用带有格式项的字符串来重构文件名,则需要使用两种不同的语法,从而在编写它们时产生更大的手动错误机会 - 这太容易了错误地创建了一个错误的格式项字符串,该字符串不能正确地重建正则表达式模式匹配的结果,反之亦然。

【问题讨论】:

    标签: regex string .net-3.5


    【解决方案1】:

    您可以使用正则表达式(耶,元正则表达式!):

    public static string RegexInterp(Regex pattern, Dictionary<string, string> pairs) {
        string regex = pattern.ToString();
        string search;
    
        foreach(KeyValuePair<string, string> entry in pairs) 
        {
            // using negative lookbehind so it doesn't match escaped parens
            search = @"\(\?<" + entry.Key + @">.*?(?<!\\)\)"; 
            regex  = Regex.Replace(regex, search, entry.Value);
        }
    
        return Regex.Unescape(unescaped);
    }
    

    然后:

    Regex rx = new Regex(@"X(?<xid>\d\d+)-(?<xsub>\w+)\.xml");
    
    var values = new Dictionary <string, string>() {{"xid", "999"},
                                                    {"xsub", "baz"}} ;
    
    Console.WriteLine(RegexInterp(rx, values));     
    

    打印

    X999-baz.xml
    

    演示:http://ideone.com/QwI2W

    【讨论】:

      【解决方案2】:

      我可能读错了,但听起来您需要 System.Text.RegularExpressions 命名空间中的 Regex.Replace 方法。

      string pattern = "Your pattern";
      string replacement = "Your text to replace";
      Regex rgx = new Regex(pattern);
      string result = rgx.Replace(input, replacement);
      

      正则表达式库中还有其他方法可以更好地在单个字符串中容纳多个替换。

      【讨论】:

      • 在这种情况下,正则表达式实际上是input
      猜你喜欢
      • 2010-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-07
      相关资源
      最近更新 更多