last day (16 days later) » 

7:27 PM
Hi
I do not quite understand what you mean.
How to preserve newlines but reset the count back to zero after encountering one (i.e. just wrap long lines on word boundaries)?
 
7:47 PM
:48525889 Hi! The problem for me is I just have original text that may already have embedded newlines.   The pre-existing newline breaks should be preserved and reset the character count for adding other newlines.   I think this is close but I have symbols getting through...

        public static string AddLineBreaks(this string text, int maxLineLength)
        {
            string regex = @"(\r\n|\r|\n)|([^\r\n]{0," + maxLineLength + @"}\b)";

            return Regex.Replace(text, regex, m =>
 
7:58 PM
Could you please illustrate the issue? An example string literal with sample data and expected output would help a lot.
As for I have symbols getting through, note that \b matches a location between both non-word and word and word and non-word, so you might need to use something like \b(?!\w) to match the right-hand word boundary.
 
8:15 PM
first line
second line: 27 chars
third line is too long. And should be split somewhere.
fourth line is also too long. And should be split somewhere.
Using (\n)|([^\n]{0,30}\b(?!\w)) in regexstorm.net/tester shows some issue with the dots.
I headed out for a few hours. Thanks for any suggestions. It seems very close now.
  public static string AddLineBreaks(this string text, int maxLineLength)
        {
            string regex = @"(\n)|([^\n]{0," + maxLineLength + @"}\b(?!\w))";

            return Regex.Replace(text, regex, m =>
                m.Value + (m.Value.Length > 1 ? "\n\t" : ""))
                .TrimEnd('\n');
        }
 
8:54 PM
Note [^\n] = .. The dots and commas are split from the words, do you want a whitespace boundary? Use (?!\S) instead. So, do you mean if there are newlines in the text you want to remove them and decrease the maxLineLength once a newline is found? This is not possible. Probably you need to remove all \r and \n in the string and then run the regex replacement.
 
 
3 hours later…
11:57 PM
Thanks for the hints. The trick that helped it to break the long lines and leave a trailing whitespace (except newline) at the end. This way the post process can use the trailing character to sense whether the indent should be applied. The following seems to be working now:

public static string AddLineBreaks(this string text, int maxLineLength, string indent = "\t")
{
text = text.Replace("\r\n", "\n"); // to keep the regex simpler

string regex = @"(\n)|([^\n]{0," + maxLineLength + @"}(?!\S)[^\S\n]?)";
 

  last day (16 days later) »