簡體   English   中英

正則表達式提取帶有嵌套括號的字符串列表

[英]Regex to extract list of strings with nested brackets

我在js中有一堆類似的字符串:

params[0][header][name[0]]

我需要將它們分成這樣的列表:

["params", "0", "header", "name[0]"]

很容易解決,直到你到達嵌套的括號。 到目前為止,我想出的最好的是這個正則表達式:

'params[0][header][name[0]]'.match(/([^\[]+)|\[(.+?\]?)\]/g)

返回:

["params", "[0]", "[header]", "[name[0]]"]

我可以使用,但我需要一個額外的步驟來刪除不需要的括號。

我的問題是,是否有一個正則表達式可以應用於字符串並且它返回一個沒有額外括號的列表?

我在 stackoverflow 和谷歌上找不到任何解決方案。 任何幫助表示贊賞。

解析括號不是正則表達式的目的。 實際上用一堆括號解析它:

function getBrackets(str) {
    const chunks = [];
    const openBrackets = [];
    let pushedFirst = false;
    for (let i = 0; i < str.length; i ++) {
        if (str[i] == "[") {
            openBrackets.push(i);
            // for pushing the first section not enclosed in brackets
            if (!pushedFirst) {
                chunks.push(str.slice(0, i));
                pushedFirst = true;
            }
        } else if (str[i] == "]") {
            const start = openBrackets.pop();
            if (openBrackets.length == 0) {
                chunks.push(str.slice(start + 1, i));
            }
        }
    }
    return chunks;
}

console.log(getBrackets("params[0][header][name[0]]")); // ["params", "0", "header", "name[0]"]

我的解決方案並不優雅:-(

const str = "params[0][header][name[0]]"
const result = str.split(/\]\[/);

const last = result[result.length - 1];
result[result.length - 1] = last.substring(0, last.length - 1);

const first = result[0]
const idx = first.indexOf("[");
result[0] = first.substring(0, idx);
result.splice(1, 0, first.substring(idx + 1));

console.log(result);

這不是一個理想的解決方案,它只是分解您的要求並使用許多檢查來強制執行它們。 它確實假設每個“[”都有一個匹配的“]”。 它可以進一步簡化,但這只是將每個需求單獨分開,而不是在可能的情況下將它們聚集在一起。

var x = "params[0][header][name[0]]";
var y = [];
var z = "";
var count = 0;

for (let i = 0; i < x.length; i++) {
    if (x[i] != "[" && x[i] != "]") {
        z += x[i];
    }
    else if(x[i] == "[" && count==0){
        count += 1;
        y.push(z);
        z = "";
        
    }
    else if(x[i] == "["){
        z += x[i];
        count += 1;
    }
    else if(x[i] == "]" && count == 1){
        count -= 1;
    }
    if(x[i] == "]" && count > 1){
        count -= 1
        z+= x[i];
    }
    if(i == x.length-1){
        y.push(z);
    }
}

暫無
暫無

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

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