Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 包含正则表达式匹配的拆分字符串_Javascript_Regex_Parsing - Fatal编程技术网

Javascript 包含正则表达式匹配的拆分字符串

Javascript 包含正则表达式匹配的拆分字符串,javascript,regex,parsing,Javascript,Regex,Parsing,我正在用JavaScript解析一些文本。假设我有一些字符串: "hello wold <1> this is some random text <3> foo <12>" “你好,世界,这是一些随机文本foo” 我需要在数组中放置以下子字符串: myArray[0] = "hello world "; myArray[1] = "<1>"; myArray[2] = " this is some random text "; myArray[

我正在用JavaScript解析一些文本。假设我有一些字符串:

"hello wold <1> this is some random text <3> foo <12>"
“你好,世界,这是一些随机文本foo”
我需要在数组中放置以下子字符串:

myArray[0] = "hello world ";
myArray[1] = "<1>";
myArray[2] = " this is some random text ";
myArray[3] = "<3>";
myArray[4] = " foo ";
myArray[5] = "<12>";
myArray[0]=“你好世界”;
myArray[1]=“”;
myArray[2]=“这是一些随机文本”;
myArray[3]=“”;
myArray[4]=“foo”;
myArray[5]=“”;
请注意,每当遇到序列时,我都会拆分字符串


我尝试过用常规表达式拆分字符串,但是当我这样做的时候,我就失去了序列。换句话说,我以“hellow world”,“这是一些随机文本”,“foo”结尾。请注意,我松开了字符串“”,我想保留它。我将如何解决这个问题?

您需要捕获序列以保留它

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这是一些随机文本foo”
str.split(/()/);
//[“hello wold”,“这是一些随机文本”,“foo”,“foo”,“and”]

如果某些浏览器中的捕获组出现问题,您可以这样手动执行:

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 ) );
var str=“hello wold这是一些随机文本foo”,
re=//g,
结果=[],
匹配,
last_idx=0;
while(match=re.exec(str)){
push(str.slice(last_idx,re.lastIndex-match[0]。length),match[0]);
last_idx=re.lastIndex;
}
结果:推(str.slice(last_idx));

请注意,根据调查,并非所有浏览器都支持使用
.split()
捕获模式(当然它没有说哪些浏览器不支持)。@nnnnnnnn:有趣的是,我想知道哪些浏览器支持捕获模式。为了安全起见,我使用了另一种解决方案进行了更新。可能是