EDIT FOR CLARITY - I know there are ways to do this in multiple steps, or using LINQ or vanilla C# string manipulation. The reason I am using a single regex call, is because I wanted practice with complex regex patterns. - END EDIT
I am trying to write a single regular expression that will perform word wrapping. It's extremely close to the desired output, but I can't quite get it to work.
Regex.Replace(text, @"(?<=^|G)(.{1,20}(s|$))", "$1
", RegexOptions.Multiline)
This is correctly wrapping words for lines that are too long, but it's adding a line break when there already is one.
Input
"This string is really long. There are a lot of words in it.
Here's another line in the string that's also very long."
Expected Output
"This string is
really long. There
are a lot of words
in it.
Here's another line
in the string that's
also very long."
Actual Output
"This string is
really long. There
are a lot of words
in it.
Here's another line
in the string that's
also very long.
"
Note the double "
" between sentences where the input already had a line break and the extra "
" that was put at the end.
Perhaps there's a way to conditionally apply different replacement patterns?
I.E. If the match ends in "
", use replace pattern "$1", otherwise, use replace pattern "$1
".
Here's a link to a similar question for wrapping a string with no white space that I used as a starting point.
Regular expression to find unbroken text and insert space
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…