fork download
  1. using System;
  2. using System.Text.RegularExpressions;
  3.  
  4. public class Test
  5. {
  6. public static void Main(string[] args)
  7. {
  8. var longUrl = "http://stackoverflow.com/questions/20494457/limiting-the-number-of-characters-using-regular-expression";
  9. var shortUrl = "http://stackoverflow.com/questions/20494457";
  10. Console.WriteLine(GetHtml(longUrl)); // should truncate
  11. Console.WriteLine(GetHtml(shortUrl)); // should not truncate
  12. }
  13.  
  14. public static string GetHtml(string url, int maxLength = 50)
  15. {
  16. var match = Regex.Match(url, String.Format("(https?://[^ ]{{{0}}})?[^ ]+", maxLength));
  17. var displayText = match.Groups[1].Length > 0 ? String.Format("{0}...", match.Groups[1]) : match.ToString();
  18. return String.Format("<a target=\"_blank\" href=\"{0}\">{1}</a>", match, displayText);
  19. }
  20. }
Success #stdin #stdout 0.07s 34112KB
stdin
Standard input is empty
stdout
<a target="_blank" href="http://stackoverflow.com/questions/20494457/limiting-the-number-of-characters-using-regular-expression">http://stackoverflow.com/questions/20494457/limiting-the-...</a>
<a target="_blank" href="http://stackoverflow.com/questions/20494457">http://stackoverflow.com/questions/20494457</a>