突破替换全局循环 [英] Break out of replace global loop

查看:68
本文介绍了突破替换全局循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a RegExp, doing a string replace, with global set. I only need one replace, but I'm using global because there's a second set of pattern matching (a mathematical equation that determines acceptable indices for the start of the replace) that I can't readily express as part of a regex.

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

即使有可能,我该如何突破字符串全局搜索?

If even possible, how do I break out of the string global search?

谢谢

可能的解决方案

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

A solution (that doesn't work in my scenario for performance reasons, since I have very large strings with thousands of possible matches to very complex RegExp running hundreds or thousands of times):

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() .由于您只进行一次替换,因此我利用这一事实简化了替换逻辑.

Use RegExp.exec() instead. Since you only do replacement once, I make use of that fact to simplify the replacement logic.

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()相同的行为,因为它也

This code exhibits the same behavior as String.match(), since it also increments the index by 1 if the last match is empty to prevent infinite loop.

这篇关于突破替换全局循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆