【问题标题】:I want to replace only the characters outside "" with a regular expression我只想用正则表达式替换“”之外的字符
【发布时间】:2021-01-05 07:36:28
【问题描述】:

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

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

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

boom

但我想要

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

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

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

【问题讨论】:

  • 可能最简单和最易读的方法是首先拆分字符串,然后只处理您实际想要替换的子字符串部分。

标签: javascript html regex


【解决方案1】:

你可以使用

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

详情

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

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

查看 JavaScript 演示:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-01
    • 2023-03-21
    相关资源
    最近更新 更多