Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/372.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.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_Replace - Fatal编程技术网

Javascript正则表达式(替换)问题

Javascript正则表达式(替换)问题,javascript,regex,replace,Javascript,Regex,Replace,我正在检查一个集合并替换所有集合 <Localisation container="test">To translate</Localisation> 翻译 带有文本的标签 下面的代码符合我的要求: var localisationRegex = new RegExp("(?:<|&lt;)(?:LocalisationKey|locale).+?(?:container|cont)=[\\\\]?(?:['\"]|(&quot;))(.+?)[

我正在检查一个集合并替换所有集合

<Localisation container="test">To translate</Localisation>
翻译
带有文本的标签

下面的代码符合我的要求:

var localisationRegex = new RegExp("(?:<|&lt;)(?:LocalisationKey|locale).+?(?:container|cont)=[\\\\]?(?:['\"]|(&quot;))(.+?)[\\\\]?(?:['\"]|(&quot;)).*?(?:>|&gt;)(.*?)(?:<|&lt;)/(?:LocalisationKey|locale)(?:>|&gt;)", "ig");

            match = localisationRegex.exec(parsedData);

            while (match != null) {
                var localeLength = match[0].length;

                var value = match[4];

                parsedData = parsedData.substr(0, match.index) + this.GetLocaleValue(value) + parsedData.substr(match.index + localeLength);

                match = localisationRegex.exec(parsedData);
            }
var localizationregex=newregexp(“(?:)(.*?(:))”,“ig”);
match=localizationregex.exec(parsedData);
while(匹配!=null){
var localelelength=match[0]。长度;
var值=匹配[4];
parsedData=parsedData.substr(0,match.index)+this.GetLocaleValue(value)+parsedData.substr(match.index+localelelength);
match=localizationregex.exec(parsedData);
}
但是,当我替换的字符串比原始字符串长时,它将开始搜索下一个匹配项的索引/位置是错误的(到目前为止)。这有时会导致找不到标记。

将该方法是否良好的(重要)问题放在一边,如果是我,我会通过使用正则表达式的函数参数来避免在源文本中建立索引的问题:

var localizer = this;
var result = parsedData.replace(localisationRegex, function(_, value) {
  return localizer.GetLocaleValue(value);
});

这将用本地化内容替换标记。

请发布一个有问题的输入/替换组合,以便我们可以重现错误。结构“+?”和“[\\]”让我感到困惑。还有,为什么不在这么复杂的事情上使用原生正则表达式语法呢?事实上,现在我想起来了,“+”和“*”子表达式会吃掉所有类型的文本。例如,如果在同一行上有两个这样的标记,那么这些标记将消耗尽可能多的文本。正是因为这个原因,用正则表达式解析XML/HTML是个坏主意。(好吧,这个原因,还有其他原因。)哦,等等,没关系;杜尔。我还没喝咖啡:-)