Lookbehinds, Regexes, and replacing \n

This is a little note for myself; don’t forget lookbehinds (and lookaheads) in regular expressions as a way of matching text that you don’t want to replace.

For example, if converting new lines to carriage-return new-lines:

// \n ---> \r\n
string output = Regex.Replace(input, "(?<!\r)\n", "\r\n"); 

This pattern find any new line character ‘\n‘ and checks if the preceding character ‘(?< … )‘ is not a carriage return ‘!\r‘.

This is neater than my having a capture group for the preceding character, and then having to put that group into my replacement pattern.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>