VB.NET regular expressions matching escape characters

Okay, that's why I hate asking RegEx questions because I usually like to find out. Plus it gets rather annoying on the other end, because people probably always ask stupid questions “why don't you just watch”?

My requirements are simple. I want to use Regex.Replaceto replace a match with a context sensitive value. For this I use MatchEvaluator. But to make things easier let's say that I map%v

I want it to %vbe escaped, so if I use it \%v, it will not match. All that must match.

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

It basically matches %vif it occurs at the beginning of a line, or if it follows any character except \. It does not capture the first part of the expression.

I know that this is not the “right” way to do this. But it worked fine until I noticed that when I use this pattern in the replacement, it includes the d character %vin the replacement (duh, right?)

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

I tried using this on Google, but the fact that the "escape character" is so heavy in RegEx that all results are focused on USING escape characters instead of selecting them using a template.

Any friends from RegEx people know how I can do this right?

+3
1

, :

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

Source: https://habr.com/ru/post/1778381/


All Articles