1

我试图找到一个正则表达式来检测字符串中的任何链接。

目前使用:/(https?:\/\/[^\s]+)/g

这工作正常,直到我看到这种链接:

http://campus.inkrement.no/Show/Index/2757798 for å lære mer

我希望它在第一时间结束 

所以它将是:

<a href='http://campus.inkrement.no/Show/Index/2757798'>http://campus.inkrement.no/Show/Index/2757798</a>&nbsp;for&nbsp;å&nbsp;lære&nbsp;mer

而不是这样:

<a href='http://campus.inkrement.no/Show/Index/2757798&nbsp;for&nbsp;å&nbsp;lære&nbsp;mer'>http://campus.inkrement.no/Show/Index/2757798&nbsp;for&nbsp;å&nbsp;lære&nbsp;mer</a>

有人知道吗?

4

3 回答 3

2

我认为你应该在这里使用负前瞻

就像是:

/(https?:\/\/(?:(?!&nbsp;)[\S])+)/g

[\S]将匹配任何非空格

(?!&nbsp;)只有在没有&nbsp;前方的情况下

?:将阻止捕获此组(可选)

于 2013-11-08T07:25:26.900 回答
1

你可以在你的表达式中添加几个字符来得到这个:

/(https?:\/\/[^\s]+?)(?=&nbsp;)|(https?:\/\/[^\s]+)/g

样本:

http://campus.inkrement.no/Show/Index/2757798&nbsp;for&nbsp;å&nbsp;lære&nbsp;mer

输出:

http://campus.inkrement.no/Show/Index/2757798

于 2013-11-08T07:26:29.377 回答
0

不会/(https?:\/\/[^\s]+?)&nbsp;/g做的伎俩?请注意您也匹配第一个&nbsp;,因此您需要将其添加到您的替换字符串中。总是有结束&nbsp;吗?

于 2013-11-08T07:16:50.890 回答