2015-12-13 23 views
0

我正在尋找某種文件的小解析器,而我必須完成的一件事是找到一行是否在另一行的內部一個,用縮進(空格或製表符)來定義它。查找一個字符串行是嵌套還是另一行的孩子

例子:

This is the main line 
    This is a nested or child line 

我試圖通過讀取行​​的第一個字符的位置,並將其與前一個像這樣的東西比較確定的:

var str = '  hello'; 
str.indexOf(str.match(/\S|$/).shift()); 

我確信這不是最好的方式,它看起來很可怕,我還有其他問題需要解決,比如檢查縮進是由空格(2或4)還是製表符,還是傳遞/保持先前的狀態行(對象)。

此外,行可以無限嵌套,當然,我正在尋找更好的和高性能的算法(或想法)或模式,而不是簡單的檢查,我認爲這樣做相對容易,但容易出錯。我相信它已經被解析器和編譯器工作的人解決了。


編輯:

str.search(/\S/); 

@Oriol提案看起來好多了

+1

也許這看起來更好:'str.search(/ \ S /)' – Oriol

+0

這是好多了,感謝@Oriol –

+0

這是爲「行可以嵌套」,或「行可以無限嵌套」?因爲這對於如何實現解決方案有所不同 –

回答

1

這通常是你寫一個解析器,而不是單純依靠正則表達式之類的話。如果嵌套決定了深度,那麼需要解決兩個問題: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. 
    } 
} 
相關問題