如何匹配参考样式的降价链接?

时间:2013-08-24 08:05:34

标签: javascript

我有兴趣使用Javascript查找文本字符串中的所有引用式markdown链接。所以我想要以下内容:

  • [all the things][things] => "things"
  • [something] => "something"

但不是:

  • [o hai](http://example.com)
  • [o hai] (http://example.com)

换句话说,一个开放的方括号后跟一个紧密的方括号,捕捉里面的文字,但不一样,后跟一组圆括号。

有意义吗?谢谢!

1 个答案:

答案 0 :(得分:1)

例如:

/(?:\[[\w\s]*\])?(\[[\w\s]*\])(?!\s*\()/
 ^--------------^ - possibly first [...], ?: - non-capturing group
                 ^-----------^ - followed by [...]
                              ^-------^ - not followed by "   (" - spaces + (

> [all the things][things]".match(/(?:\[[\w\s]*\])?(\[[\w\s]*\])(?!\s*\()/)[1]
"[things]"
> "[something]".match(/(?:\[[\w\s]*\])?(\[[\w\s]*\])(?!\s*\()/)[1]
"[something]"
> "[o hai](http://example.com)".match(/(?:\[[\w\s]*\])?(\[[\w\s]*\])(?!\s*\()/)
null
> "[o hai] (http://example.com)".match(/(?:\[[\w\s]*\])?(\[[\w\s]*\])(?!\s*\()/)
null