Inside the regular expression, the Match Evaluator function (anonymous method) does the grunt job and saves newlines in StringBuilder. We do not use the return value of the Regex.Replace method because we simply use the Match Evaluator function as a function to perform line breaks inside a regular expression call - just for that, because I think it's cool.
using System; using System.Text; using System.Text.RegularExpressions;
strInput is what you want to convert.
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 > MAX_LEN || m.Index == bmark && m.Length >= 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
It is also worth noting that the second condition in the if expression in the Match m.Index == bmark && m.Length >= MAX_LEN implied as an exceptional condition if the word is longer than 60 characters (or longer than the specified maximum length) - it will not be broken here, but just saved on one line by itself - I think you might want to create a second formula for this condition in the real world for transferring it or something else.
source share