Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 455
dhirschl Avatar asked Apr 13 '11 13:04

dhirschl


1 Answers

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.

like image 98
Ahmad Mageed Avatar answered Sep 28 '22 16:09

Ahmad Mageed