這通常是你寫一個解析器,而不是單純依靠正則表達式之類的話。如果嵌套決定了深度,那麼需要解決兩個問題:1)找到任意線的深度,2)遍歷線和軌跡集,對於每一行,前一行的深度值較低。
第一個是平凡的,如果你熟悉JavaScript中的正則表達式的功能:
function getDepth(line) {
// find leading white space
var ws = str.match(/^(\s+)/);
// no leading white space?
if (ws === null) return 0;
// leading white space -> count the white space symbols.
// obviously this goes wrong for mixed spaces and tabs, and that's on you.
return ws[0].split('').length;
}
第二部分是沒有價值的,所以你有幾種選擇。你可以循環遍歷所有行,並跟蹤行號列表,當你更深入的時候推入列表並在列表中彈出列表,或者你可以建立一個簡單的樹結構(這通常要好得多,因爲它可以讓你更輕鬆地擴展其功能)使用標準的樹木建築。
function buildTree(lines, depths) {
if (!depths) {
var depths = lines.map(e => getDepth);
return buildTree(lines, depths);
}
var root = new Node();
for(var pos=0, end=lines.length; pos<end; pos++) {
var line = lines[pos];
var depth = depths[pos];
root.insert(line, depth);
}
}
用一個簡單的Node
對象,當然
var Node = function(text, depth) {
this.children = [];
this.line = text.replace(/^\s+/,'');
this.depth = depth;
}
Node.prototype = {
insert: function(text, depth) {
// this is where you become responsible: we need to insert
// a new node inside of this one if the depths indicate that
// is what should happen, but you're on the hook for determining
// what you want to have happen if the indentation was weird, like
// a line at depth 12 after a line at depth 2, or vice versa.
}
}
也許這看起來更好:'str.search(/ \ S /)' – Oriol
這是好多了,感謝@Oriol –
這是爲「行可以嵌套」,或「行可以無限嵌套」?因爲這對於如何實現解決方案有所不同 –