首页 > 解决方案 > 正则表达式:替换单词前面

问题描述

我有这个字符串:

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.expectan\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]);
});

标签: javascriptregex

解决方案


您可以使用替换,它是捕获组的回调。

^(\*\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)


推荐阅读