Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript正则表达式解析smilies并忽略URL_Javascript_Regex_Parsing - Fatal编程技术网

Javascript正则表达式解析smilies并忽略URL

Javascript正则表达式解析smilies并忽略URL,javascript,regex,parsing,Javascript,Regex,Parsing,我想解析来自用户的输入,并用笑脸的图像替换所有的笑脸“代码”。我遇到了一个问题,当用户编写url时,http://和https://的:/。我用于:/replace的当前正则表达式是“//g”,我需要帮助更改它,以便在http://或https:// 输入示例 请查看此链接以帮助您:)。如果没有帮助,请使用 应该解析到输出 Please have a look at this link http://stackoverflow.com that could help you <img sr

我想解析来自用户的输入,并用笑脸的图像替换所有的笑脸“代码”。我遇到了一个问题,当用户编写url时,http://和https://的:/。我用于:/replace的当前正则表达式是“//g”,我需要帮助更改它,以便在http://或https://

输入示例

请查看此链接以帮助您:)。如果没有帮助,请使用

应该解析到输出

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
请查看此链接http://stackoverflow.com 那会对你有帮助的。如果没有帮助,请使用https://www.google.com

下面是一个regex101.com示例:(如您所见,http://和https://也在此处被选中并替换)

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

/((?:https?|ftps?):\/)|:\//ig
请参阅,
((?:https?| ftps?):\/)
是前面带有
http
ftp
:/
,它们可以在
replace
中的匿名函数中恢复

以下是一个片段:

var str='请查看此链接http://stackoverflow.com 这可以帮助你:)。如果没有帮助,请使用https://www.google.com. 现在,一个困难的问题是:/;
var result=str.replace(/((?:https?| ftps?):\/)\:\//ig,函数(m,grp1){
返回grp1?grp1:“”;
});

警报(结果)也许这不是严格的正则表达式答案,但您可以用一些临时常量替换
http://
,然后将smiles替换并回滚常量为
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
;

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

:\/([^\/]|$)
替换为:

<img ... >$1
1美元
说明-其中有两种变体:

  • :\/[^\/]
    -
    :\
    ,下一个字符不是
    \
    ,但这将忽略文本末尾的微笑(微笑后没有字符)

  • :\/$
    -在文本末尾加上微笑


  • 由于整个正则表达式将smiley与其后的char(例如空格)匹配,因此我们必须将该mached char(如果它是文本结尾,则为nothing)替换为string。

    URL可以有http或httpsI以外的协议,就像这个正则表达式一样简单,但是它要求smiley“代码”和单词之间有一个空格。i、 e.如果用户写入“.不帮助:/”将不会对其进行分析。如果我们不必为用户做这件事就好了:)我已经用更灵活的解决方案替换了代码。您可以向第一个捕获组添加更多排除项
    ((?:https?| ftps?)\/)
    。例如,要排除
    gopher:
    使用
    ((?:https?| ftps?| gother):\/)
    。可能
    (\b(?:https?\ftps?):\/)
    更安全(因为
    http
    ftp
    必须是整字,因为
    \b
    )。看起来不错,我能看到的唯一问题是它与smiley code之后的下一个字符匹配。如果用户写入,例如“:/:/:/:/:/”,彼此之后没有空格:。它还匹配一个空格,所以在替换中,我必须在末尾添加一个空格。