使用正则表达式限制字符数

时间:2013-12-10 12:23:43

标签: c# regex

我使用以下正则表达式将字符串中的所有网址转换为完整的超链接:

var r = new Regex("(https?://[^ ]+)");
return r.Replace(Action, "<a target=\"_blank\" href=\"$1\">$1</a>");

我想限制标签内显示的字符数,如果可能的话,如果超出长度则添加省略号。

e.g。 http://myurl.com/my/route/th ...

我尝试过使用外观来实现这个目标,并且想知道是否有人有更好的解决方案?

3 个答案:

答案 0 :(得分:1)

以下正则表达式会为您提供

后的内容
((https?://[^ ]){20}[^ ]+)

这样做是创建2个捕获组

  1. 捕获整个网址
  2. 将网址捕获到特定长度(在此示例中为20)
  3. 所需要的只是添加截断,例如

    Regex.Replace(Action, "((https?://[^ ]){20}[^ ]+)", "<a target=\"_blank\" href=\"$1\">$2...</a>"));
    

    action中查看。


    正如评论中所指出的,上述结果会导致...被附加到所有URL(即使是不超过长度的URL)。鉴于使用的可变性,这里的正则表达式可能不可行。但是,我们可以通过对正则表达式的一些小调整和一些简单的字符串操作来解决这个问题,例如。

    var match = Regex.Match(Action, "(https?://[^ ]{50})?[^ ]+");
    // if the display part group has matched something, we need to truncate
    var displayText = match.Groups[1].Length > 0 ? String.Format("{0}...", match.Groups[1]) : match.ToString();
    Console.WriteLine(String.Format("<a target=\"_blank\" href=\"{0}\">{1}</a>", match, displayText));
    

    我更新了example

答案 1 :(得分:1)

通过使用函数进行替换,最好通过自定义match evaluator解决。

string Action = "Somebody turn http://stackoverflow.com/questions/20494457/limiting-the-number-of-characters-using-regular-expression into a link please.";
var r = new Regex("(https?://\\S+)");
return r.Replace(Action,
    match => {
        string display = match.Value;
        if (display.Length > 30)
        {
            display = display.Substring(0, 30) + "...";
        }
        return "<a target=\"_blank\" href=\"" + match.Value + "\">" + display + "</a>";
    });

返回:

Somebody turn <a target="_blank" href="http://stackoverflow.com/questions/20494457/limiting-the-number-of-characters-using-regular-expression">http://stackoverflow.com/quest...</a> into a link please.

答案 2 :(得分:0)

我不认为用简单的正则表达式替换可以做到这一点,但幸运的是.NET允许你执行更复杂的替换。首先,我们设置正则表达式来捕获一个组中URL开始后的第一个(例如)25个字符,以及第二个可选组中的任何其他字符:

var r = new Regex("(https?://[^ ]{1,25})([^ ]+)?");

如果在URL开始后少于25个字符,则第二个组将完全失败,但它是可选的,因此它不会使正则表达式整体失败。

然后,在更换时,我们会在决定是否添加点时检查第二组是否匹配:

var s = r.Replace(
    Action,
    m => string.Concat(
        "<a target=\"_blank\" href=\"",
        m.Value,
        "\">",
        m.Groups[1].Value,
        (m.Groups[2].Success ? "..." : ""),
        "</a>"));

输入

"hello http://www.google.com world
 http://www.loooooooooooooooooooooooooooooooooooooooooong.com !"

我得到输出

hello <a target="_blank" href="http://www.google.com">http://www.google.com</a>
world <a target="_blank"
    href="http://www.loooooooooooooooooooooooooooooooooooooooooong.com">
    http://www.loooooooooooooooooooo...</a> !
相关问题