javascript - 正则表达式:替换单词前面
问题描述
我有这个字符串:
const string = `
* @test
* pm.test("Response time is less than 200ms", function() {
* pm.expect(pm.response.responseTime).to.be.below(500);
* });
* pm.test("Successful POST request", function() {
* pm.expect(pm.response.code).to.be.oneOf([200, 201, 202]);
* });
`;
我想对其进行一些更改,例如在每个 an 前面和每个pm.expect
an\n\t
前面pm.test
添加\n
const cleaned = string
.replace(/\n/g, "")
.replace(/\s */g, ' ')
.replace(/\*/g, "")
.replace(/@[a-z]+/g, "")
.replace(/{(pm.expect)/g,'\n\t') // the problem is here
.replace(/(pm.test)/g,'\n') // the problem is here
我最终想要这样的东西:
pm.test("Response time is less than 200ms", function() {
pm.expect(pm.response.responseTime).to.be.below(500);
});
pm.test("Successful POST request", function() {
pm.expect(pm.response.code).to.be.oneOf([200, 201, 202]);
});
解决方案
您可以使用替换,它是捕获组的回调。
^(\*\s*)(?:(pm.test)|(pm.expect)
| | |__________ (Group 3, g3)
| |______________________ (Group 2, g3)
|_________________________________ (Group 1, g1)
const string = `
* @test
* pm.test("Response time is less than 200ms", function() {
* pm.expect(pm.response.responseTime).to.be.below(500);
* });
* pm.test("Successful POST request", function() {
* pm.expect(pm.response.code).to.be.oneOf([200, 201, 202]);
* });
`;
let op = string.replace(/^(\*\s*)(?:(pm.test)|(pm.expect))/gm,(match,g1,g2,g3)=>{
if(g2){
return g1 + '\n\t' + g2
} else {
return g1 + '\n' + g3
}
})
console.log(op)
推荐阅读
- tfs - 在“创建工作项的副本”功能上分配字段映射
- python - 为什么 scikit-learn StandardScaler 不支持 keep_nan 操作?
- c++ - C++20 中的 constexpr 数学函数
- c# - 如何从实体框架代码优先方法自动增加 oracle 表?
- html - 使用选择文件输入来包装上传按钮的类
- java - 在java中更改图像大小
- javascript - 带有 Oauth 的 Quillinoz api
- dotnetnuke - DNN9 文件上传
- javascript - JS Date 构造函数替代
- java - JasperReports:内置函数的编译错误