【问题标题】:How can I regex replace all spaces in matched text with underscore? (Javascript)如何正则表达式用下划线替换匹配文本中的所有空格? (Javascript)
【发布时间】:2020-05-09 01:02:15
【问题描述】:

我有以下:

enum class test {
    something1, // this is a comment
    something2, // something else
    something3,
};

我想把它转换成:

enum class test {
    something1 | this_is_a_comment
    something2 | something_else
    something3,
};

所以我需要用下划线替换 // 之后所有文本的空格

到目前为止我有这个:

/\,.*\/\/\s*(.*)/g

这将选择我想要的文本但是如何替换空格?

我真的不需要使用正则表达式,所以任何解决方案都值得赞赏!

【问题讨论】:

  • 结果中的下划线在哪里?
  • cmets 例如这是一条评论 > this_is_a_comment

标签: javascript regex string replace


【解决方案1】:

replace() 方法中使用函数。该函数可以对该捕获组执行嵌套替换。

let str = `enum class test{
    something1, // this is a comment
    something2, // something else
    something3,
};`;

let new_str = str.replace(/\,.*\/\/\s*(.*)/g, (match0, match1) => ' | ' + match1.replace(/ /g, '_'));
console.log(new_str);

.

【讨论】:

  • 这正是我想要的,谢谢 :)
【解决方案2】:

您可以使用函数作为替换的第二个参数。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

它将以完整匹配然后按顺序调用每个组。这意味着您可以像这样解决您的问题:

str.replace(/\,.*\/\/\s*(.*)/g, (match, group1) => " | " + group1.replace(/\s/g, "_"))

【讨论】:

    猜你喜欢
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多