views:

106

answers:

4

I don't claim to be a RegEx guru at all, and I am a bit confused on what this statement is doing. I am trying to refactor and this is being called on a key press and eating a lot of CPU.

Regex.Replace(_textBox.Text, "(?<!\r)\n", Environment.NewLine);

Thanks.

+8  A: 

The regular expression (?<!\r)\n will match any \n character that is not preceeded by a \r character. The syntax (?<!expr) is a negative look-behind assertion and means that expr must not match the part that’s before the current position.

Gumbo
+1  A: 

It's replacing every instance where there is a \n not preceeded by a \r with a Environment.NewLine string. This string is the platform specific newline (on Windows it will be the string "\r\n")

JaredPar
@Jared the NewLine string will vary based on the environment, so it won't always be \r\n
Gavin Miller
@LFSR, true. I'll update my answer
JaredPar
A: 

The regular expression will match any newline character \n that isn't preceded by a carriage return character \r with the platform specific NewLine character(s).

The NewLine character is:

  • \r\n for non-Unix platforms
  • \n for Unix platforms
Gavin Miller
+1  A: 

In addition to the answers explaining what the regex does (match all \n's without a \r before it), I'd just like to point out that this use of Replace() is most likely never necessary, unless you have users hellbent on typing just \n's somehow. And even then, you probably don't need it on the keypress, just when the text as a whole is used (i.e. after the data is submitted somehow).

And if that was put in there to sanitize copy-pasted text, then you can refactor it to only run when a large amount of the text has been changed.

Sean Nyman