【问题标题】:How to match URLs but not in brackets如何匹配 URL 但不在括号中
【发布时间】:2016-08-26 22:20:20
【问题描述】:

我的网址可能在这样的括号内:

[[!;;;;http://example.com/foo]some text]

如何匹配 URL 但不是当它们在括号中时,some text 也可能是 URL。我需要将所有网址替换为该格式。

到目前为止,我有匹配 URL 的正则表达式:

var url_re = /(\bhttps?:\/\/(?:(?:(?!&[^;]+;)|(?=&amp;))[^\s"'<>\]\[)])+\b)/gi;

示例输入:

http://example.com/foo [[!;;;;http://example.com/foo]some text] http://example.com/foo

输出:

[[!;;;;http://example.com/foo]http://example.com/foo] [[!;;;;http://example.com/foo]some text] [[!;;;;http://example.com/foo]http://example.com/foo]

【问题讨论】:

标签: javascript regex url


【解决方案1】:

您可以添加一个(?![^[\]]*]) 否定前瞻,这将避免在没有任何其他[] 的关闭] 之前匹配模式:

\b(https?:\/\/(?:(?:(?!&[^;]+;)|(?=&amp;))[^\s"'<>\][)])+)\b(?![^[\]]*])

并替换为[[!;;;;$1]$1]。见regex demo

另一种选择是匹配并捕获[...[...]...] 中的所有内容,然后使用String.replace() 中的回调来正确处理每个捕获,但上述内容似乎“更干净”且更直接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    相关资源
    最近更新 更多