我有以下内容:
文字:
field id =“25”ordinal =“15”value =“& $ 01234567890- $ 2000 - ”
正则表达式:
(小于?=值= “)。*(?=”)
替换字符串:
&安培; $ $ 09876543210- 1998 -
当我在Expresso中运行Regex Replace时 - 它会使应用程序崩溃。
如果我在C#中运行Regex.Replace,我会收到以下异常:
的ArgumentException
解析“& $ 01234567890- $ 2000-” - 捕获组编号必须小于或等于Int32.MaxValue。
答案 0 :(得分:11)
替换模式中的$N
是指第N 个捕获组,因此正则表达式引擎认为您要引用捕获组号“09876543210”并抛出{{1} }。如果要在替换字符串中使用文字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);
,这样它最终不会在字符串后面的另一个双引号中匹配,或者.*?
,以便它匹配除双引号之外的所有内容。更新后的模式为:[^"]*
或@"(?<=value="").*?(?="")"
。如果您从未期望value属性为空,我建议在任何模式中使用@"(?<=value="")[^""]*(?="")"
而不是+
,以确保它与至少一个字符匹配。