簡體   English   中英

正則表達式考慮到嵌套括號將字符串按空格分割

[英]Regex split string by spaces taking into account nested brackets

我知道這個問題已經被問過/回答過幾次,但是不幸的是,到目前為止,我嘗試過的所有解決方案都無法解決我的問題。 我需要這樣分割:

contrast(200%) drop-shadow(rgba(0, 0, 0, 0.5) 0px 0px 10px)

到這個:

contrast(200%)
drop-shadow(0px 0px 10px rgba(0,0,0,.5))

通過遵循此解決方案 ,我目前正在這樣做:

myString = "contrast(200%) drop-shadow(rgba(0, 0, 0, 0.5) 0px 0px 10px)"
myString.match(/[^\(\s]+(\(.*?\)+)?/g)

但這給了我:

contrast(200%)
drop-shadow(rgba(0, 0, 0, 0.5)  <== notice the missing second ) here
0px    <== unwanted, should go with previous one
0px    <== unwanted, should go with previous one
10px)  <== unwanted, should go with previous one

因為正則表達式不能捕獲所有的右括號...

這是我的解決方案:

function splitBySpaces(string){
    var openBrackets = 0, ret = [], i = 0;
    while (i < string.length){
        if (string.charAt(i) == '(')
            openBrackets++;
        else if (string.charAt(i) == ')')
            openBrackets--;
        else if (string.charAt(i) == " " && openBrackets == 0){
            ret.push(string.substr(0, i));
            string = string.substr(i + 1);
            i = -1;
        }
        i++;
    }

    if (string != "") ret.push(string);
    return ret;
}

您可以使用以下代碼在嵌套括號之外的空格/制表符上拆分字符串:

 function splitOnWhitespaceOutsideBalancedParens() { var item = '', result = [], stack = 0, whitespace = /\\s/; for (var i=0; i < text.length; i++) { if ( text[i].match(whitespace) && stack == 0 ) { result.push(item); item = ''; continue; } else if ( text[i] == '(' ) { stack++; } else if ( text[i] == ')' ) { stack--; } item += text[i]; } result.push(item); return result; } var text = "contrast(200%) drop-shadow(rgba(0, 0, 0, 0.5) 0px 0px 10px)"; console.log(splitOnWhitespaceOutsideBalancedParens(text)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM