【问题标题】:Unable to RegEx Replace无法进行正则表达式替换
【发布时间】:2011-04-13 13:52:20
【问题描述】:

我有以下几点:

文字:

field id="25" ordinal="15" value="& $01234567890-$2000-"

正则表达式:

(?

替换字符串:

&$09876543210-$2000-


当我在 Expresso 中运行 Regex Replace 时 - 它会使应用程序崩溃。

如果我在 C# 中运行 Regex.Replace,我会收到以下异常:

ArgumentException

解析 "& $01234567890-$2000-" - 捕获组数必须小于或等于 Int32.MaxValue。

【问题讨论】:

    标签: c# .net regex exception


    【解决方案1】:

    替换模式中的$N 指的是Nth 捕获组,因此正则表达式引擎认为您要引用捕获组号“09876543210”并抛出ArgumentException。如果您想在替换字符串中使用文字 $ 符号,则将其加倍以转义符号:& $$09876543210-$$2000-

    string input = @"field id=""25"" ordinal=""15"" value=""& $01234567890-$2000-""";
    string pattern = @"(?<=value="").*(?="")";
    string replacement = "& $$09876543210-$$2000-";
    string result = Regex.Replace(input, pattern, replacement);
    

    此外,您的模式目前是贪婪的,可能会超出预期。为了使它不贪婪,使用.*?,这样它就不会在字符串后面的另一个双引号之外匹配,或者[^"]*,这样它就可以匹配除双引号之外的所有内容。更新后的模式将是:@"(?&lt;=value="").*?(?="")"@"(?&lt;=value="")[^""]*(?="")"。如果您从未期望 value 属性为空,我建议在任何模式中使用 + 而不是 * 以确保它至少匹配一个字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-29
      • 1970-01-01
      相关资源
      最近更新 更多