开发者

Unable to RegEx Replace

I have the following:

Text:

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

Regular Expression:

(?<=value=").*(?=")

开发者_如何转开发

Replacement String:

& $09876543210-$2000-


When I run Regex Replace in Expresso - it crashes the application.

If I run Regex.Replace in C#, I receive the following Exception:

ArgumentException

parsing "& $01234567890-$2000-" - Capture group numbers must be less than or equal to Int32.MaxValue.


A $N in the replacement pattern refers to the Nth capture group, so the regex engine thinks you want to refer to capture group number "09876543210" and throws the ArgumentException. If you want to use a literal $ symbol in the replacement string then double it up to escape the symbol: & $$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);

Also, your pattern is currently greedy and may match more than intended. To make it non-greedy use .*? so it doesn't end up matching beyond another double quote later in the string, or [^"]* so that it matches everything except a double quote. The updated pattern would be: @"(?<=value="").*?(?="")" or @"(?<=value="")[^""]*(?="")". If you never expect the value attribute to be empty I suggest using + instead of * in any of the patterns to ensure it matches at least one character.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜