【问题标题】:Javascript regex parsing smilies and ignoring urlsJavascript正则表达式解析表情符号并忽略网址
【发布时间】:2015-10-15 11:32:42
【问题描述】:

我想解析用户的输入并将所有笑脸“代码”替换为笑脸图像。当用户写一个 url 然后 http:// 和 https:// 的 :/ 被替换时,我遇到了一个问题。我用于 :/ 替换的当前正则表达式是“/://g”,我需要帮助更改它,因此它不会替换 :/ 如果它位于 http:// 或 https://

输入示例

请查看此链接http://stackoverflow.com,它可以帮助您:)。如果它没有帮助:/那么请使用https://www.google.com

应该解析输出

Please have a look at this link http://stackoverflow.com that could help you <img src="/smile.png"/>. If it does not help <img src="/sidesmile.png"/> then please use https://www.google.com

这是一个 regex101.com 示例:https://regex101.com/r/bB6vK2/1(如您所见,此处也选择并替换了 http:// 和 https://)

【问题讨论】:

    标签: javascript regex parsing


    【解决方案1】:

    您可以匹配并捕获您想要保留的:/,然后只匹配将被替换的:/

    /((?:https?|ftps?):\/)|:\//ig
    

    看,((?:https?|ftps?):\/) 是前面有httpftp:/,它们可以在replace 内部的匿名函数中恢复。

    这是一个sn-p:

    var str = 'Please have a look at this link http://stackoverflow.com that could help you :). If it does not help :/ then please use https://www.google.com. Now, a difficult one:/';
    var result = str.replace(/((?:https?|ftps?):\/)|:\//ig, function (m, grp1) {
       return grp1 ? grp1 : '<img src="/sidesmile.png"/>';
      });
    alert(result);

    【讨论】:

    • 我喜欢这个简单的正则表达式,但是它要求笑脸“代码”和单词之间有一个空格。即如果用户写“..没有帮助:/”,它将不会被解析。如果我们不必为用户做这个就好了:)
    • 我已将代码替换为更灵活的解决方案。随意向第一个捕获组((?:https?|ftps?):\/) 添加更多排除项。例如。排除 gopher: 使用 ((?:https?|ftps?|gother):\/)。可能(\b(?:https?|ftps?):\/) 更安全(因为httpftp 必须是完整的单词然后由于\b)。
    【解决方案2】:

    更新了:/ 的正则表达式:

    :\/([^\/]|$)
    

    替换为:

    <img ... >$1
    

    解释 - 这有两个变种:

    1. :\/[^\/] - :\ 下一个字符不是\,但这会在文本末尾省略微笑(笑脸后没有字符)。

    2. :\/$ - 文字末尾的笑脸。

    由于整个正则表达式匹配笑脸和它后面的字符(例如空格),所以我们必须把那个经过处理的字符(或者如果它是文本的结尾则什么都没有)来替换字符串。

    【讨论】:

    • 看起来不错,我能看到的唯一问题是它匹配笑脸代码之后的下一个字符。如果用户写例如“:/:/:/:/”,彼此之间没有空格:regex101.com/r/jO7cW7/1。它还匹配一个空格,所以在替换中我必须在末尾添加一个空格。
    【解决方案3】:

    也许这不是严格的正则表达式答案,但您可以考虑用一些临时常量替换 http://,将微笑替换并回滚常量到 http://

    input
      .replace(/http(s?):\/\//g, '__http$1__') // escape http:// keyword
      .replace(/:\//g, 'SMILE') // do the smiles replacement
      .replace(/__http(s?)__/g, 'http$1://') // rollback constant
    ;
    

    【讨论】:

    • 一个 URL 可以有 http 或 https 以外的协议
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    相关资源
    最近更新 更多