using System; using System.Text.RegularExpressions; public class Test { public static void Main(string[] args) { var longUrl = "http://stackoverflow.com/questions/20494457/limiting-the-number-of-characters-using-regular-expression"; var shortUrl = "http://stackoverflow.com/questions/20494457"; Console.WriteLine(GetHtml(longUrl)); // should truncate Console.WriteLine(GetHtml(shortUrl)); // should not truncate } public static string GetHtml(string url, int maxLength = 50) { var match = Regex.Match(url, String.Format("(https?://[^ ]{{{0}}})?[^ ]+", maxLength)); var displayText = match.Groups[1].Length > 0 ? String.Format("{0}...", match.Groups[1]) : match.ToString(); return String.Format("{1}", match, displayText); } }