javascript - 正则表达式查找括号中的字符串并替换

标签 javascript regex

我有一个字符串:你好[@Some Person](#/path/to/person)。你好吗?你的咖啡在哪里? [@Another Person](#/path/to/another) 说你不擅长正则表达式。

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

因此上述示例的最终输出应该是:Hello there Some Person。你好吗?你的咖啡在哪里?另一个人说你不擅长正则表达式。

到目前为止我已经:

> 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 周围的双引号:

str.replace(re, "$1")

关于javascript - 正则表达式查找括号中的字符串并替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38131084/

相关文章:

javascript - jQuery 在页面标题中获取特定值

javascript - React Native - 同步运行函数

javascript - 在所选 td 的底部中心显示 div

正则表达式检查字符串是否是由逗号分隔的字母数字或单个字母数字字符串

python - 匹配字符串中除 python 中大括号前面的任何单词

java - 使用 core-nlp 的 DocumentPreprocessor 拆分句子时处理连词

javascript - JQuery 语句仅在 success 函数内发出警报后才起作用

javascript - 为 intl-tel-input 插件添加淡入淡出效果

javascript - 解析node.js中的WHERE子句

regex - 为什么/\w+ :/and/\S+:/handle backtracking differently?