首页 > 解决方案 > 我只想用正则表达式替换“”之外的字符

问题描述

我想用正则表达式得到结果

var text = "\"1test2test3\"test123test45test\"67test89\"";

text.replaceAll(/\"(.*)\"/g, "boom");

boom

但我想要

var text = "\"1test2test3\"test123test45test\"67test89\"";

text.replaceAll(????, "boom");

"\"1test2test3\"boom123boom45boom\"67test89\"";

标签: javascripthtmlregex

解决方案


您可以使用

.replace(/("[^"]*")|test/g, (x,y) => y ? y : "boom")

详情

  • ("[^"]*")- 捕获组 1: a ",然后是除 a 之外的任何零个或多个字符",然后是 a"
  • |- 或者
  • test- 一个test字符串。

(x,y) => y ? y : "boom"替换意味着只要 Group 1 ( ) 匹配,y则返回此组值,否则(如果test在所有其他上下文中找到)boom则返回。

请参阅 JavaScript 演示:

var text = "\"1test2test3\"test123test45test\"67test89\"";
console.log(text.replace(/("[^"]*")|test/g, (x,y) => y ? y : "boom"));


推荐阅读