开发者

VB.NET Regular Expressions, matching escape characters

开发者 https://www.devze.com 2023-01-28 14:38 出处:网络
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\"

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?


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")
0

精彩评论

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