Is it possible using Regex.Replace to match a string, but only replace a portion of that matched string? Some way to mark part of the string that should be replaced with the replacement text parameter?
+5
A:
You can use groups to insert parts of the original string, or you can use lookbehind and lookahead.
Examples
Using Groups:
someString = Regex.Replace(someString, @"(before)content(after)", "$1new content$2");
Using lookaround:
someString = Regex.Replace(someString, @"(?<=before)content(?=after)", @"new content");
SLaks
2010-07-14 20:15:47
Looking forward to the examples :)
Winforms
2010-07-14 20:17:25
Works but instead of \1 you need $1
Winforms
2010-07-14 20:19:44
I will accept when it lets me
Winforms
2010-07-14 20:20:07
+1 I had no idea you could do this, nice!
northpole
2010-07-14 20:20:36
@SLaks: Why do you have the ?<= and the ?=, without them everything works perfect. With them it doesn't work.
Winforms
2010-07-14 21:41:28
@Winforms: Those are lookaround assertions. It works for me: `Regex.Replace("abc", @"(?<=a)b(?=c)", "q")` prints `aqc`.
SLaks
2010-07-14 22:06:33