VB.NET Regular Expressions, matching escape characters

Ok, so I hate asking RegEx questions because I like to figure them out myself usually. Plus it gets fairly annoying on the other end because people probably ask stupid "why dont you just look it up" questions all the time.

My requirement is simple. I want to use Regex.Replace to replace a Match with a context sensitive value. I use the MatchEvaluator for this. But to make things simpler lets say I'm matching %v

I want %v to be escapable, so if I use \%v it will not match. Anything else should match.

The pattern I came up with is this: (?:[^\\]|^)%v

It basically matches %v if it occurs at the beginning of the string, or if it follows any character except \. It doesn't capture the first part of the expression.

I know this isn't the "right" way to do it. But it worked just fine until I noticed that when I use this pattern in a replace, it includes the character before %v in the replacement(duh, right?)

So, if I have ThisIsAValue:%v and I do Regex.Replace, replacing with the string Value, my result will be ThisIsAValueValue instead of ThisIsAValue:Value

I've tried googling this but the fact that "escape character" is so heavy in RegEx, all the results are geared towards the USAGE of escape characters instead of picking them out with a pattern.

Any RegEx savvy people know how I can do this correctly?

Answers


You can manually put the start character back in, by capturing it and including it in the replace value:

Regex.Replace("ThisIsAValue:%v", "([^\\]|^)%v", "$1Value")

Need Your Help

Display some lines from file in java

java file

I have a txt file that contains 10 lines, and I would like to write Java code to display lines 3 through 5.

Debugging Help: C++ error

c++ debugging

I am getting this error: