[link](url)
我正在尝试编写一个正则表达式来查找上面的模式并返回以下代码:
<a href="url">link</a>
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
正在捕获里面的字符()
。