Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx to replace @ unless it is preceded by /

Tags:

.net

regex

I need a regular expression that will be used to replace @ with /@, unless the the @ is preceded by <. I have been fiddling with RegExHero to try to accomplish this, but it is not quite right. It is important to note that I am fairly clueless when it comes to regular expressions.

Here is what I have tried:

Regular Expression [^<]\@

Replacement String &/@

Target String Flip@

This almost works, in that it will not replace Flip<@. But then it does not work because it replaces Flip@ to Fli/@. Basically, I need to keep the original character in the case that the symbol is not preceded by an angle bracket.

like image 418
Dave Johnson Avatar asked Dec 12 '22 14:12

Dave Johnson


2 Answers

The way you've worded is exactly what the definition of a negative lookbehind assertion is.

(?<!<)@

In general,

(?<!foo)bar

means, "bar" not following "foo". A positive lookbehind,

(?<=foo)bar

would mean, oppositely, "bar" following "foo".

There are also lookaheads, e.g.

bar(?=foo)

meaning "bar" followed by "foo".

like image 60
slackwing Avatar answered Jan 11 '23 20:01

slackwing


The reason your expression does not work as expected is that your expression captures the character preceding the @ sign, making it part of the replacement target. You need to change [^<] with (?<!<) to use the non-capturing negative lookbehind. The final expression should look like this:

(?<!<)\@
like image 28
Sergey Kalinichenko Avatar answered Jan 11 '23 20:01

Sergey Kalinichenko