2012-01-13 138 views
1

我正在使用JavaScript解析一些文本。比方說,我有一些字符串:包含正則表達式匹配的拆分字符串

"hello wold <1> this is some random text <3> foo <12>" 

我需要把下面的子字符串數組:每當我遇到<「數字」

myArray[0] = "hello world "; 
myArray[1] = "<1>"; 
myArray[2] = " this is some random text "; 
myArray[3] = "<3>"; 
myArray[4] = " foo "; 
myArray[5] = "<12>"; 

注意,我劈裂字符串>序列

我試過用正則表達式分割字符串/<\d{1,3}>/但是當我這樣做的時候,我放棄了<「number」>序列。換句話說,我最終得到了「世界的和諧」,「這是一些隨機文本」,「富」。請注意,我將字符串「< 1>」,「< 3>」和「< 12>」我想保留該字符串。我將如何解決這個問題?

+0

可能重複[使用Javascript - string.split(正則表達式)保持分隔符](http://stackoverflow.com/questions/4204210/javascript-string-splitregex-keep-seperators) – outis 2012-02-19 19:34:48

回答

11

您需要捕獲序列以保留它。

var str = "hello wold <1> this is some random text <3> foo <12>" 

str.split(/(<\d{1,3}>)/); 

// ["hello wold ", "<1>", " this is some random text ", "<3>", " foo ", "<12>", ""] 

的情況下有在某些瀏覽器中捕獲組的問題,你可以手工做這樣的:

var str = "hello wold <1> this is some random text <3> foo <12>",  
    re = /<\d{1,3}>/g, 
    result = [], 
    match, 
    last_idx = 0; 

while(match = re.exec(str)) { 
    result.push(str.slice(last_idx, re.lastIndex - match[0].length), match[0]); 

    last_idx = re.lastIndex; 
} 
result.push(str.slice(last_idx)); 
+2

請注意,根據[MDN](https://developer.mozilla.org/en/JavaScript/Reference/ Global_Objects/String/Split#Description)並非所有的瀏覽器都支持用'.split()'捕獲模式(儘管它當然不會說es不)。 – nnnnnn 2012-01-13 00:32:32

+0

@nnnnnn:有趣的,我不知道哪些。爲了安全起見,我更新了一個不同的解決方案。 – 2012-01-13 00:42:40