javascript - 跳出替换全局循环

标签 javascript regex replace global break

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

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");

如果可能的话,如何摆脱字符串全局搜索?

谢谢

可能的解决方案

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

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/

相关文章:

javascript - 字符串内双引号的正则表达式

Javascript正则表达式多个字符分割

javascript - 在字符串javascript中找到标签的位置

PHP 反向 Preg_match

SQL 左/分隔字符

javascript - 将值分配给另一个具有动态分配键的对象内的对象

javascript - 在 Meteor 中使用图像集

javascript - 将对象添加到 inlineImages sendEmail 参数

regex - 如何用单个空格替换换行符/换行符,但前提是它们在开始/结束正则表达式中?

python - 如果其他矩阵值等于 pandas 中的某个值,则将值替换为 NaN