javascript - 我只想用正则表达式替换“”之外的字符
问题描述
我想用正则表达式得到结果
var text = "\"1test2test3\"test123test45test\"67test89\"";
text.replaceAll(/\"(.*)\"/g, "boom");
boom
但我想要
var text = "\"1test2test3\"test123test45test\"67test89\"";
text.replaceAll(????, "boom");
"\"1test2test3\"boom123boom45boom\"67test89\"";
解决方案
您可以使用
.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"));
推荐阅读
- elasticsearch - 在 apm 代理初始化期间云提供商的自动发现过程中出现意外错误
- reactjs - 如何使用 popperjs 在 React 中为多个项目使用一个弹出框?
- arrays - 有没有办法根据 Google 表格中的数组中的数据返回列值?
- swift - Swift 中 __PRETTY_FUNCTION__ 的替代品是什么?
- javascript - 区分关闭浏览器/选项卡和导航离开/将浏览器切换到后台/在待机状态下切换设备
- c# - Microsoft 标识平台 Asp.Net c# 和 Visual Studio
- node.js - Angular 依赖问题:@types/node: '{' or ';' 预期的
- bash - 使用 ncatted 时,在 bash 脚本中保留双引号会产生意想不到的结果
- php - 如何基于php中的平面数组在css中构建树(id,parent_id)
- c# - 取消所有 MS Graph API 结果分页的辅助方法