-4
[link](url)

我正在尝试编写一个正则表达式来查找上面的模式并返回以下代码:

<a href="url">link</a>
4

1 回答 1

4

通过阅读教程,我猜。

str = str.replace(/\[([^\]]*)\]\(([^)]*)\)/g, '<a href="$2">$1</a>');

我承认,这看起来有点令人生畏。这是一个解释:

/        # just the delimiter for the regex (like " for a string)
\[       # match a literal [
(        # start capturing group $1 for later access
  [^\]]  # match any character except ]
  *      # 0 or more of those (as many as possible)
)        # end of capturing group $1
\]       # match a literal ]
\(       # match a literal (
(        # start capturing group $2 for later access
  [^)]   # match any character except )
  *      # 0 or more of those (as many as possible)
)        # end of capturing group $2
\)       # match a literal )
/        # end of regex
g        # make regex global to replace ALL occurrences

$1然后我们$2在替换字符串中引用两个捕获的组。$1正在捕获里面的字符[]并且$2正在捕获里面的字符()

于 2012-11-18T18:33:07.763 回答