views:

198

answers:

2

When using a multi-line TextBox (AcceptsReturn="True") in Silverlight, line feeds are recorded as \r rather than \r\n. This is causing problems when the data is persisted and later exported to another format to be read by a Windows application.

I was thinking of using a regular expression to replace any single \r characters with a \r\n, but I suck at regex's and couldn't get it to work.

Because there may be a mixture of line endings just blindy replacing all \r with \r\n doesn't cut it.

So two questions really...

If regex is the way to go what's the correct pattern?

Is there a way to get Silverlight to respect it's own Environment.NewLine character in TextBox's and have it insert \r\n rather just a single \r?

+2  A: 

I don't know Silverlight at all (and I find the behavior you're describing very strange), but perhaps you could try searching for \r(?!\n) and replacing that with \r\n.

\r(?!\n) means "match a \r if and only if it's not followed by \n".

If you also happen to have \n without preceding \rs and want to "normalize" those too, then search for \r(?!\n)|(?<!\r)\n and replace with \r\n.

(?<!\r)\n means "match a \n if and only if it's not preceded by \r".

Tim Pietzcker
+1  A: 

I don't know Silverlight, but I imagine (I hope!) there's a way to get it to respect Environment.NewLine—that would be a better approach. If there isn't, however, you can use a regex. I'll assume you have text which contains all of \r, \n, and \r\n, and never uses those as anything but line endings—you just want consistency. (If they show up as non-line ending data, the regex solution becomes much harder, and possibly impossible.) You thus want to replace all occurrences of \r(?!\n)|(?<!\r)\n with \r\n. The first half of the first regex matches any \r not followed by a \n; the second half matches a lone \n which wasn't preceded by a \r.

The fancy operators in this regex are termed lookaround: (?=...) is a positive lookahead, (?<=...) is a positive lookbehind, (?!...) is a negative lookahead, and (?<!...) is a negative lookbehind. Each of them is a zero-width assertion like ^ or $; they match successfully without consuming input if the given regex succeeds/fails (for positive/negative, respectively) to match after/before (for lookahead/lookbehind) the current location in the string.

Antal S-Z
+1 for having had the exact same (good) idea at the exact same time :)
Tim Pietzcker
Well said, sir :)
Antal S-Z
Thanks guys, just the piece of regex I was looking, it worked perfectly. Silverlight seems to have a few quirky behaviours, didn't even notice this until one of the users exported to csv and complained about all the smily characters.
Ian Oakes