How to find and replace a particular character but only if it is in quotes?

后端 未结 6 2539
刺人心
刺人心 2021-02-19 01:23

Problem: I have thousands of documents which contains a specific character I don\'t want. E.g. the character a. These documents contain a variety of characters, but

6条回答
  •  情歌与酒
    2021-02-19 02:13

    /(["'])(.*?)(a)(.*?\1)/g
    

    With the replace pattern:

    $1$2$4
    

    As far as I'm aware, VS Code uses the same regex engine as JavaScript, which is why I've written my example in JS.

    The problem with this is that if you have multiple a's in 1 set of quotes, then it will struggle to pull out the right values, so there needs to be some sort of code behind it, or you, hammering the replace button until no more matches are found, to recurse the pattern and get rid of all the a's in between quotes

    let regex = /(["'])(.*?)(a)(.*?\1)/g,
    subst = `$1$2$4`,
    str = `"a"
    "helapke"
    Not matched - aaaaaaa
    "This is the way the world ends"
    "Not with fire"
    "ABBA"
    "abba",
    'I can haz cheezburger'
    "This is not a match'
    `;
    
    
    // Loop to get rid of multiple a's in quotes
    while(str.match(regex)){
        str = str.replace(regex, subst);
    }
    
    const result = str;
    console.log(result);

提交回复
热议问题