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 ---> rn
string output = Regex.Replace(input, "(?<!r)n", "rn"); 

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.

Lookbehinds, Regexes, and replacing n

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.