2012-01-13 217 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