正则表达式在括号中找到字符串并替换

时间:2016-06-30 18:49:39

标签: javascript regex

我有一个字符串:Hello there [@Some Person](#/path/to/person). How are you? Where is your coffee? [@Another Person](#/path/to/another) said you are not great at regex.

我想将[@Some Person](#/path/to/person)等所有模式替换为Some Person

因此上述示例的最终输出应为:Hello there Some Person. How are you? Where is your coffee? Another Person said you are not great at regex.

到目前为止,我有:

> var re = /\[@([\w\s]+)\](\(\S+\))/g
> str.match(re)
> ["[@Some Person](#/path/to/person)", "[@Another Person](#/path/to/another)"]
// matches but not quite what I want.
> str.replace(re, $1)
> "Hello there undefined. How are you? Where is your coffee? undefined said you are not great at regex."
// does not replace as expected.

这是我的regex sandbox。我想用str.replace来获得我想要的东西。不确定这是否可行。看起来应该是这样。请帮忙。

1 个答案:

答案 0 :(得分:2)

您忘记了$1周围的双引号:

str.replace(re, "$1")