Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Inside a Regular expression, the Match Evaluator function (an anonymous method) does the grunt work and stores the newly sized lines into a StringBuilder. We don't use the return value of Regex.Replace method because we're just using its Match Evaluator function as a feature to accomplish line breaking from inside the regular expression call - just for the heck of it, because I think it's cool.</p> <pre><code>using System; using System.Text; using System.Text.RegularExpressions; </code></pre> <p><strong>strInput</strong> is what you want to convert the lines of. </p> <pre><code>int MAX_LEN = 60; StringBuilder sb = new StringBuilder(); int bmark = 0; //bookmark position Regex.Replace(strInput, @".*?\b\w+\b.*?", delegate(Match m) { if (m.Index - bmark + m.Length + m.NextMatch().Length &gt; MAX_LEN || m.Index == bmark &amp;&amp; m.Length &gt;= MAX_LEN) { sb.Append(strInput.Substring(bmark, m.Index - bmark + m.Length).Trim() + Environment.NewLine); bmark = m.Index + m.Length; } return null; }, RegexOptions.Singleline); if (bmark != strInput.Length) // last portion sb.Append(strInput.Substring(bmark)); string strModified = sb.ToString(); // get the real string from builder </code></pre> <p>It's also worth noting the second condition in the if expression in the Match Evaluator <code>m.Index == bmark &amp;&amp; m.Length &gt;= MAX_LEN</code> is meant as an exceptional condition in case there is a word longer than 60 chars (or longer than the set max length) - it will not be broken down here but just stored on one line by itself - I guess you might want to create a second formula for that condition in the real world to hyphenate it or something.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload