【问题标题】:Replace and RegEx issue替换和正则表达式问题
【发布时间】:2014-12-06 13:14:24
【问题描述】:

我正在使用 LinqToTwitter API 使用 Twitter API。我正在尝试格式化推文文本。但我有替换问题,下面的正则表达式是我从 twitter 获得的字符串

@TheNational: ICYMI: Louvre be first museum in Asia to show a painting http://t.co/fmp http://t.c…

现在我正在使用下面的代码将所有 URL 替换为链接以进行显示。

首先我创建正则表达式来获取链接

private readonly Regex _parseUrls = new Regex("(?<Protocol>\\w+):\\/\\/(?<Domain>[\\w@][\\w.:@]+)\\/?[\\w\\.?=%&=\\-@/$,]*", RegexOptions.IgnoreCase | RegexOptions.Compiled);

然后我匹配它们并替换如下

foreach (var urlMatch in _parseUrls.Matches(tweetText))
  {
    Match match = (Match)urlMatch;
    tweetText = tweetText.Replace(match.Value, string.Format("<a href=\"{0}\" target=\"_blank\">{0}</a>", match.Value));
  }

正则表达式按预期工作得很好,但现在替换出现问题,因为字符串中的两个链接都以 http://t.co 开头,它每次都替换第一次出现。

有人帮我解决我所缺少的。

【问题讨论】:

    标签: c# regex replace


    【解决方案1】:

    这不是进行替换的正确方法。

    使用Regex.Replace 方法:

    _parseUrls.Replace(tweetText, "<a href=\"$&\" target=\"_blank\">$&</a>");
    

    或者,更好的是,使用 HTML 编码:

    _parseUrls.Replace(tweetText,
                       match => string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>",
                                              match.Value,
                                              WebUtility.HtmlEncode(match.Value))
                      );
    

    例如,这会将 URL 中的任何 &amp;amp; 转换为 &lt;a&gt; 标记内的 &amp;amp;。您甚至应该对字符串的其余部分进行编码:如果有人在推特上发布了一些 HTML 代码,您希望按原样显示它而不是解释它。

    您的原始方法的问题是 _parseUrls.Matches(tweetText) 每次迭代都会再次匹配替换的文本。

    【讨论】:

      猜你喜欢
      • 2011-09-07
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多