JavaScript正则表达式模式

时间:2012-11-18 18:28:04

标签: javascript regex

[link](url)

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

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

1 个答案:

答案 0 :(得分:4)

By reading a tutorial, I guess.

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正在捕获()内的字符。