gpt4 book ai didi

javascript - 跳出替换全局循环

转载 作者:行者123 更新时间:2023-11-30 12:49:34 25 4
gpt4 key购买 nike

我有一个 RegExp,用全局集进行字符串替换。我只需要一个替换,但我正在使用全局,因为还有第二组模式匹配(确定替换开始可接受索引的数学方程式),我不能轻易将其表示为正则表达式的一部分。

var myString = //function-created string
myString = myString.replace(myRegex, function(){
if (/* this index is okay */){

//!! want to STOP searching now !!//
return //my return string

} else {
return arguments[0];
//return the string we matched (no change)
//continue on to the next match
}
}, "g");

如果可能的话,我该如何突破字符串全局搜索?

谢谢

可能的解决方案

一个解决方案(由于性能原因在我的场景中不起作用,因为我有非常大的字符串,其中有数千个可能匹配非常复杂的 RegExp 运行数百或数千次):

var matched = false;
var myString = //function-created string
myString = myString.replace(myRegex, function(){
if (!matched && /* this index is okay */){
matched = true;
//!! want to STOP searching now !!//
return //my return string

} else {
return arguments[0];
//return the string we matched (no change)
//continue on to the next match
}
}, "g");

最佳答案

使用RegExp.exec()反而。由于您只进行一次替换,因此我利用这一事实来简化替换逻辑。

var myString = "some string";
// NOTE: The g flag is important!
var myRegex = /some_regex/g;

// Default value when no match is found
var result = myString;
var arr = null;

while ((arr = myRegex.exec(myString)) != null) {
// arr.index gives the starting index of the match
if (/* index is OK */) {
// Assign new value to result
result = myString.substring(0, arr.index) +
/* replacement */ +
myString.substring(myRegex.lastIndex);
break;
}

// Increment lastIndex of myRegex if the regex matches an empty string
// This is important to prevent infinite loop
if (arr[0].length == 0) {
myRegex.lastIndex++;
}
}

此代码表现出与 String.match() 相同的行为,因为它也是 increments the index by 1 if the last match is empty防止无限循环。

关于javascript - 跳出替换全局循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21435986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com