如何多次执行捕获组?

时间:2016-02-24 22:27:02

标签: javascript regex

我有这个字符串:

var str = "some text start:anything can be here some other text";

这是预期的结果:

//=> some text start:anythingcanbehere some other text

换句话说,我正在尝试删除特定范围的字符串之间的所有空格。

以下是我的尝试:

(start:)(?:(\S+)(\s+))(.*)(?= some)

It works,但是我应该执行几次以达到预期的结果。如何在我的正则表达式中使用\1+来运行它几次?

2 个答案:

答案 0 :(得分:3)

使用简单的regexp替换不能做你想要的,因为捕获组只能捕获一个字符串 - 没有循环。 Javascript允许您提供一个替换函数,它可以对捕获的字符串执行更复杂的操作。

var str = "some text start:anything can be here some other text";
var newstr = str.replace(/(start:)(.*)(?= some)/, function(match, g1, g2) {
  return g1 + g2.replace(/ /g, '');
});
alert(newstr);

答案 1 :(得分:2)

replace与回调一起使用:

var repl = str.replace(/(start:.*?)(?= some\b)/, function(_, $1) { 
     return $1.replace(/\s+/g, ''); });
//=> some text start:anythingcanbehere some other text
相关问题