Regex: split string by character except if inside quotes or double quotes

Viewed 301

I need to split a string using a delimiter character (= in my example) , except if this character is inside quotes or double quotes

I succeed to do it within single quotes using \=+(?=(?:(?:[^']*'){2})*[^']*$) , or within double quotes using \=+(?=(?:(?:[^"]*"){2})*[^"]*$), but not for both, what would be the appropriate RegExp ?

Bonus: if it can also split when the character is not inside character ` , it would be perfect :)

enter image description here

enter image description here

What I need :

enter image description here

Edit: Javascript example to reproduce ( https://jsfiddle.net/cgnorhm0/ )

function splitByCharExceptInsideString(str, delimiterChar) {
    // split line by character except when it is inside quotes
    const escapedChar = delimiterChar.replace(/[-[\]{}()*+!<=:?./\\^$|#\s,]/g, "\\$&");
    const regSplit = new RegExp(escapedChar + `+(?=(?:(?:[^']*'){2})*[^']*$)`);
    const splits = str.split(regSplit);
    return splits ;
}

const testStr = `image.inside {
    sshagent(credentials: ['ssh-creds']) {
        env.GIT_SSH_COMMAND="ssh -T -o StrictHostKeyChecking=no"
        env.GIT_SSH_COMMAND2='ssh -T -o StrictHostKeyChecking=no'
    }
}`;
const delimiterChar = '=';

const splitLs = splitByCharExceptInsideString(testStr,delimiterChar);
console.log(splitLs);
2 Answers

lookahead and lookbehind don't consume character so you can use multiple of them together. you can use

\=+(?=(?:(?:[^"]*"){2})*[^"]*$)(?=(?:(?:[^']*'){2})*[^']*$)(?=(?:(?:[^`]*`){2})*[^`]*$)

Regex Demo

The regex below finds = characters that are not inside `, ", or ' pairs.

const regex = /=(?=.*)(?=(?:'.*?'|".*?"|`.*?`).*?)/;

Behavior with your example: enter image description here

Related