我的数据如下:
var data = "AAAAAAAAAAAAAAAA 925 940 TTTTTTTTTTTTTTTT 3001 3016 15 AAAAAAAAAAAAAAAA 2418 2433 TTTTTTTTTTTTTTTT 3000 3015 15";
我想用空格分隔的三个连续数字来分割这些数据。 所以,我试过这个:
var split_data = data.split(/\d+\s+\d+\s+\d+\s+/);
我想保持拆分值与之前的值相加。我想要以下输出:
AAAAAAAAAAAAAAAA 925 940 TTTTTTTTTTTTTTTT 3001 3016 15
AAAAAAAAAAAAAAAA 2418 2433 TTTTTTTTTTTTTTTT 3000 3015 15
在Perl中,可以使用以下模式轻松实现:
@split_data = split(/\d+\s+\d+\s+\d+\K\s+/,$data);
Perl支持\K
运算符,但JavaScript没有。我该怎么办?
答案 0 :(得分:1)
您可以轻松地进行匹配而不是拆分。
(.*?\d+\s+\d+\s+\d+\s*)
参见演示。
https://regex101.com/r/mT0iE7/17
var re = /(.*?\d+\s+\d+\s+\d+\s*)/img;
var str = 'AAAAAAAAAAAAAAAA 925 940 TTTTTTTTTTTTTTTT 3001 3016 15 AAAAAAAAAAAAAAAA 2418 2433 TTTTTTTTTTTTTTTT 3000 3015 15';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
答案 1 :(得分:0)
您可以在此处使用split
,但您需要使用反向字符串技巧来解决JavaScript中缺少的后置功能。</ p>
function revStr(str) {
return str.split('').reverse().join('');
}
var data = "AAAAAAAAAAAAAAAA 925 940 TTTTTTTTTTTTTTTT 3001 3016 15 AAAAAAAAAAAAAAAA 2418 2433 TTTTTTTTTTTTTTTT 3000 3015 15";
var split_data = revStr(data).split(/\s+(?=\d+\s+\d+\s+\d+)/i);
var arrayLength = split_data.length;
for (var i = 0; i < arrayLength; i++) {
document.getElementById("res").innerHTML += revStr(split_data[i]) + "<br/>";
}
&#13;
<div id="res"/>
&#13;