2012-11-18 21 views
-3
[link](url) 

我想写一个正则表达式查找上面的图案,并返回下面的代码:JavaScript正则表达式模式

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

您将首先从信誉良好的来源学习正则表达式的基础知识,如[MDN](https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions)。 –

+0

也许使用一些已经存在的解决方案,如Markdown; [pagedown](http://code.google.com/p/pagedown/)是一个JavaScript Markdown转换器和编辑器,与此处在StackOverflow中使用的类似。 – Gumbo

回答

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

+1

我真的希望人们不会鼓励这类问题。 –

+0

@ user1689607我明白了你的观点,但我相信3分钟的降薪和4分钟内的封闭问题令人沮丧。而且我觉得只有教程链接会是一个狡猾的答案。 –

+0

是的教程链接本身就是一个不好的答案。我当然不批评你的答案的内容......只是它的存在。 ;-) –