tags:

views:

194

answers:

1

I have a really long string. I would like to add a linefeed every 80 characters. Is there a regular expression replacement pattern I can use to insert "\r\n" every 80 characters? I am using C# if that matters.

I would like to avoid using a loop.

I don't need to worry about being in the middle of a word. I just want to insert a linefeed exactly every 80 characters.

+4  A: 

I don't know the exact C# names, but it should be something like

str.Replace("(.{80})", "$1\r\n");

The idea is to grab 80 characters and save it in a group, then put it back in (I think "$1" is the right syntax) along with the "\r\n".

(Edit: The original regex had a + in it, which you definitely don't want. That would completely eliminate everything except the last line and any leftover pieces--a decidedly suboptimal result.)

Note that this way, you will most likely split inside words, so it might look pretty ugly.

You should be looking more into word wrapping if this is indeed supposed to be readable text. A little googling turned up a couple of functions; or if this is a text box, you can just turn on the WordWrap property.

Also, check out the .Net page at regular-expressions.info. It's by far the best reference site for regexes that I know of. (Jan Goyvaerts is on SO, but nobody told me to say that.)

Michael Myers
This worked perfectly. The string does not contain words. Thank you.
Chris