There is probably no need to involve regular expressions in something so simple. Take this extension method:
public static string Abbreviate(this string text, int length) { if (text.Length <= length) { return text; } char[] delimiters = new char[] { ' ', '.', ',', ':', ';' }; int index = text.LastIndexOfAny(delimiters, length - 3); if (index > (length / 2)) { return text.Substring(0, index) + "..."; } else { return text.Substring(0, length - 3) + "..."; } }
If the string is short enough, it is returned as-is. Otherwise, if the word boundary is in the second half of the line, it is “gracefully” cut off at that point. If not, it cuts off the hard path under the desired length.
If the line is disabled at all, an ellipsis ("...") is added to it.
If you expect the string to contain constructors based on an unnatural language (such as a URL), you need to tweak it to ensure good behavior in all circumstances. In this case, working with a regular expression might be better.
source share