【问题标题】:Javascript regexp replace capturingJavascript 正则表达式替换捕获
【发布时间】:2019-01-27 20:10:12
【问题描述】:

我正在尝试在 Nodejs 应用程序中使用正则表达式。我通常在Python中使用它,它似乎有some differences

问题来了: 我有这个字符串\newcommand{\hello}{@replace},只有当我在第一个卷曲手镯中找到\hello 时,我才想在第二个卷曲手镯中用REPLACED 替换@replace。所以预期的结果是:\newcommand{\hello}{REPLACED}

我试试这个:

r = new RegExp('\\newcommand{\\hello}{(.*?)}');
s = '\\newcommand{\\hello}{@replace}';
s.replace(r, 'REPLACED');

但是什么都没有被替换……有什么线索吗?

【问题讨论】:

标签: javascript node.js regex


【解决方案1】:
r = new RegExp(/\\newcommand{\\hello}{@replace}/);
s = '\\newcommand{\\hello}{@replace}';
let a = s.replace(r, '\\newcommand{\\hello}{REPLACED}');

console.log(a)

输出将是:"\newcommand{\hello}{REPLACED}"

【讨论】:

  • 好吧,我很愚蠢...我相信当我按下回车键时 Firefox 控制台会返回。女巫返回我"\\newcommand{\\hello}{@replace}" 但是当用console.log 打印它时它的作品!谢谢
【解决方案2】:

您根本不需要正则表达式来执行这种操作。您可以简单地在第一个参数处使用字符串:

s = '\\newcommand{\\hello}{@replace}';
s.replace('@replace', 'REPLACED'); // => "\newcommand{\hello}{REPLACED}"

【讨论】:

  • 你说得对!我专注于 RegExp,但您的解决方案也有效。
【解决方案3】:

我不确定我是否正确理解了这个问题。这是你要找的吗?

function replaceWith(myReplacement) {
    var original = "\\newcommand{\\hello}{@replace}";
    var regex = "{\\hello}{@replace}";

    return original.replace(regex, `{\\hello}{${myReplacement}}`)
};


console.log(replaceWith("World"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 2014-06-19
    • 2010-11-19
    • 2010-11-12
    • 2016-09-23
    • 1970-01-01
    • 2011-09-02
    相关资源
    最近更新 更多