【问题标题】:Replace matches with regex用正则表达式替换匹配项
【发布时间】:2016-10-10 14:22:37
【问题描述】:

我正在尝试替换美元符号之间的文本匹配项。

所以Some text and $some text that matches$.里面的文字$match$应该被替换掉。

我试过了

text.replace(/\$.*?\$/g, function (match) {
  return '_' + match + '_';
}

这行得通。问题是我想在这个函数中评估匹配,但有时评估不起作用,在这些情况下我只想返回原始匹配。所以它就像

text.replace(/\$.*?\$/g, function (match) {
  try {
    return evaluate(match);
  } catch (e) {
    return match;
  }
}

但是对于我当前的正则表达式,匹配包含原始文本中的美元符号。我希望它省略美元符号,但如果评估失败,那么我想要原来的美元符号。

我能做的是

text.replace(/\$.*?\$/g, function (match) {
  try {
    return evaluate(match.replace(/\$/g, ''));
  } catch (e) {
    return match;
  }
}

但不是更优雅的方式吗?

【问题讨论】:

  • 你所拥有的看起来不错,除了 try..catch,你应该尝试从 evaluate 函数返回一些东西,而不是让它抛出错误。

标签: javascript regex replace


【解决方案1】:

这样的事情可能会做:

const evaluate = function(str) {
    if (str && str.startsWith("t")) {return str.toUpperCase();}
    throw "Gotta hava a 'T'";
};

"ab$test$cd $something$ that is $tricky$.".replace(/\$([^$]*)\$/g;, function(str, match) {
    try {
        return evaluate(match);
    } catch(e) {
        return str;
    }
}); //=> "abTESTcd $something$ that is TRICKY."

但我同意这样的评论,即您最好返回来自evaluate 的不同信号(undefined?null?),而不是为这种情况而抛出。然后函数体可以简单地类似于:

        return evaluate(match) || str;

重点是正则表达式中的捕获组:/\$([^$]*)\$/g;,它成为替换函数的参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-16
    • 2022-11-29
    • 2016-11-04
    • 2015-11-30
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    相关资源
    最近更新 更多