Tuesday, March 15, 2011

How to form this Regex

Suppose the string is:

string item = "t-ewrwerwerwerwer\r-rr\wrjkwlr";

I want to Replace all - except when it is preceded by r.

So resut will be

string cleanItem = "tewrwerwerwerwer\r-rr\wrjkwlr"'

What regular expression can be used?

From stackoverflow
  • A replacement on (?<!r)- by an empty string should do the trick I think.

  • (?<!r)-
    

    As long as your regex flavor supports zero-width look-behind, that is.

  • I think this regular expression is a little more efficient:

    -(?<!r-)
    

    Or if your language doesn’t support negative look-behind assertions, use this expression:

    (^|[^r])-
    

    and replace it by \1 (first matching group).

0 comments:

Post a Comment