Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/391.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 - Fatal编程技术网

Javascript 如何多次执行捕获组?

Javascript 如何多次执行捕获组?,javascript,regex,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) 同样如此,但我应该执行几次以达到预期的结果。。我如何在

我有这个字符串:

var str = "some text start:anything can be here some other text";
以下是预期结果:

//=> some text start:anythingcanbehere some other text
换句话说,我正试图删除这样一个字符串的特定范围之间的所有空格


以下是我尝试过的:

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

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

简单的正则表达式替换不能满足您的需要,因为捕获组只能捕获一个字符串——没有循环。Javascript允许您提供一个函数作为替换,它可以对捕获的字符串执行更复杂的操作

var str=“一些文本开始:任何东西都可以在这里或其他文本”;
var newstr=str.replace(/(开始:)(.*)(?=some)/,函数(匹配,g1,g2){
返回g1+g2。替换(//g',);
});

警报(newstr)简单的regexp替换无法实现您想要的功能,因为捕获组只能捕获一个字符串——没有循环。Javascript允许您提供一个函数作为替换,它可以对捕获的字符串执行更复杂的操作

var str=“一些文本开始:任何东西都可以在这里或其他文本”;
var newstr=str.replace(/(开始:)(.*)(?=some)/,函数(匹配,g1,g2){
返回g1+g2。替换(//g',);
});

警报(newstr)使用回调替换

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

使用
替换为回调:

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

使用
g
修饰符。你的Javascript代码在哪里?@Barmar,我在发布我的question@Barmar我不想要任何javascript代码。我只想知道如何使用
\1+
多次执行一个捕获组,在这种情况下,这个捕获组
(?:(\S+)(\S+)
@stack:如果要多次运行它,需要javascript使用
g
修饰符。您的javascript代码在哪里?@Barmar,我在发布我的question@Barmar我不想要任何javascript代码。我只想知道如何使用
\1+
多次执行一个捕获组,在这种情况下,这个捕获组
(?:(\S+)(\S+)
@stack:如果要多次运行它,需要使用javascript,因为在
某些
之前缺少空间,因此,您将在结果中获得
heresome
。您缺少
some
之前的空格,因此您将在结果中获得
heresome