How to split string while ignoring portion in parentheses?

前端 未结 5 1484
南方客
南方客 2020-12-11 17:51

I have a string that I want to split into an array by using the commas as delimiters. I do not want the portions of the string that is between parentheses to be split thoug

5条回答
  •  没有蜡笔的小新
    2020-12-11 18:23

    I don't like to have large opaque regular expressions in my code so I used a different solution. It still makes use of regex but I think is somewhat more transparent.

    I use a simpler regex to replace any commas within parenthesis with a special string. I then split the string by commas, then within each resulting token I replace the special string with a comma.

        splitIgnoreParens(str: string): string[]{
        const SPECIAL_STRING = '$REPLACE_ME';
    
        // Replaces a comma with the special string
        const replaceComma = s => s.replace(',',SPECIAL_STRING);
        // Vice versa
        const replaceSpecialString = s => s.replace(SPECIAL_STRING,',');
    
        // Selects any text within parenthesis
        const parenthesisRegex = /\(.*\)/gi;
    
        // Withing all parenthesis, replace comma with special string.
        const cleanStr = str.replace(parenthesisRegex, replaceComma);
        const tokens = cleanStr.split(',');
        const cleanTokens = tokens.map(replaceSpecialString);
    
        return cleanTokens;
    }
    

提交回复
热议问题