Safari上的Regex错误?前面的标记是不可量化的



我得到错误"?前面的标记是不可量化的";在Safari:中执行Regex时

const replaceWord = (word, highlightColor) => {
return `<span style='color: ${highlightColor} !important; font-weight: bold !important;'>${word}</span>`;
};
let message = `masterworld worldwide world business businesses
<br />
Gamification_in_the.Business.World.html
<br />
Gamification_in_the_Business>World.html
<br/ >
Gamification_in_the_Business_World.html
<br />
Gamification-in-the-Business-World.html`;
message = message.replace(
// it was like this before: /* /bbusinessb|bworldb/gi, */
// but since it need also to match business_world as two words, I changed to:
/(?<![^W_])business(?![^W_])|(?<![^W_])world(?![^W_])/gi,
(matched, offset, text) => {
if (matched) {
return replaceWord(matched, 'red');
}
return "";
}
);
document.write(message);

但Safari正在崩溃。我明白了"?前面的标记是不可量化的";

https://regex101.com/r/JpmF92/1

有没有等效的Regex可以让我搜索文本中的单词并将_(下划线(视为分隔符?

当搜索"0"时;商业世界";我应该得到:

Business.World = match
Business_World = match
Business-World = match
Business>World = match
Business+World = match
businessworld = NO match

正确,为了解决此问题,在替换时,需要使用匹配反向上下文的捕获组。在替换中,您所需要添加的只是反向引用。

请参阅此JavaScript演示:

let message = "masterworld worldwide world business businesses<br />Gamification_in_the.Business.World.html<br />Gamification_in_the_Business>World.html<br/ >Gamification_in_the_Business_World.html<br />Gamification-in-the-Business-World.html";
message = message.replace(
/([W_]|^)(business|world)(?![^W_])/gi,
"$1<span style='color: red !important; font-weight: bold !important;'>$2</span>"
);
document.body.innerHTML = message;

现在,模式看起来像([W_]|^)(business|world)(?![^W_]):

  • ([W_]|^)-组1($1(:非单词字符或下划线或字符串开头
  • (business|world)-第2组:两个单词之一
  • (?![^W_])-一个负前瞻,用于检查下一个字符是非单词还是_

现在,在替换模式中,$1表示捕获到组1中的字符(边界字符或字符串的开头(,$2表示捕获到第2组中的单词。

如果你想用回调函数保持替换逻辑,你需要记住捕获的值也需要传递给这个函数:

const replaceWord = (left, word, highlightColor) => {
return `${left}<span style='color: ${highlightColor} !important; font-weight: bold !important;'>${word}</span>`;
};
let message = "masterworld worldwide world business businesses<br />Gamification_in_the.Business.World.html<br />Gamification_in_the_Business>World.html<br/ >Gamification_in_the_Business_World.html<br />Gamification-in-the-Business-World.html";
message = message.replace(
/([W_]|^)(business|world)(?![^W_])/gi,
(matched, group1, group2, offset, text) => {
return replaceWord(group1, group2, 'red');
}
);
document.body.innerHTML = message;

注:

  • if (matched)没有意义,如果代码进入回调函数,则总是存在匹配(只有在存在匹配时才会调用(
  • (matched, group1, group2, offset, text) => return replaceWord(group1, group2, 'red')现在具有组值,group1是左上下文,group2是匹配的word
  • replacedWord现在也采用left参数,返回值以left文本为前缀

最新更新