How to use regex to add lines?

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

I would like to avoid using a loop.

I don’t have to worry about being in the middle of a word. I just want to insert a translation string exactly every 80 characters.

0
source share
1 answer

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

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

The idea is to capture 80 characters and save them in a group, and then return them back (I think "$ 1" is the correct syntax) along with "\ r \ n".

( Edit: There was a + in the original regular expression that you definitely don't want to. This will completely eliminate everything except the last line and any remaining parts - clearly suboptimal results.)

Note that in this way you are likely to divide the words inside so that it looks pretty ugly.

You should look more at word wrapping if it really should be readable text. A little googling appeared a couple of functions ; or if it is a text field, you can simply enable the WordWrap property .

Also, check out the .NET page at regular-expressions.info. This is by far the best regex help site I know of. (Jan Goewaerts is on SO, but no one told me to say that.)

+5
source

All Articles