JS正则表达式后行断言在Firefox和Safari中无法工作

9
我有以下的正则表达式,在Chrome中工作,但在Firefox或Safari中会导致错误。我需要修改它使其工作。 有人可以帮助一下吗?先感谢了!
正则表达式:/(?=)(.*?)(?<=<\/tag>)/
基本上,我必须匹配< tag >和< /tag >之间的任何字符,并且需要保留这两个标签。我将此表达式用作数组.split的参数。
输入:“The quick brown fox jumps over the lazy dog”
操作:input.split(regex)
输出:["The quick brown ", "fox", " jumps over the lazy ", "dog"]
2个回答

12

Firefox和Has
Safari目前还不支持后行断言,您可以使用捕获组(用于将我们正在拆分的模式添加到输出中),并在<tag> </tag>处进行拆分。

let str = "The quick brown <tag>fox</tag> jumps over the lazy <tag>dog</tag>"

let regex = /(<tag>.*?<\/tag>)/

console.log(str.split(regex).filter(Boolean))


1
它可以工作。感谢您的回复。我意识到我在最初的正则表达式中过度设计了。干杯! - webedward
在这种情况下,不需要使用 g 修饰符,因为它是 split 的默认行为。 - Wiktor Stribiżew

1
也许,
<tag>.*?<\/tag>|[^<>]+

会正常工作:

测试

function regularExpression(regex, str) {
 let m, arr = [];
 while ((m = regex.exec(str)) !== null) {
  // This is necessary to avoid infinite loops with zero-width matches
  if (m.index === regex.lastIndex) {
   regex.lastIndex++;
  }


  m.forEach((match, groupIndex) => {
   arr.push(match.trim());
   console.log(`Found match, group ${groupIndex}: ${match}`);
  });
 }
 return arr;
}

const expression = /<tag>.*?<\/tag>|[^<>]+/g;
const string = 'The quick brown <tag>fox</tag> jumps over the lazy <tag>dog</tag>';

console.log(regularExpression(expression, string));


如果您想简化/修改/探索表达式,可以在regex101.com的右上角面板中找到解释。如果您愿意,您还可以观看this link,了解它如何匹配一些示例输入。

正则表达式电路

jex.im 可视化正则表达式:

enter image description here


我试过这个方法,它可以工作,但我认为第一个答案更简单,足以满足实现要求。感谢提供可视化! - webedward

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接