【问题标题】:JS Regex lookbehind not working in firefox and safariJS Regex lookbehind 在 firefox 和 safari 中不起作用
【发布时间】:2020-02-16 00:29:23
【问题描述】:

我有以下正则表达式,它在 chrome 中工作,但在 firefox 或 safari 中导致错误。我需要修改它以使其工作。谁能帮助一个可怜的灵魂?提前致谢!

正则表达式:/(?=<tag>)(.*?)(?<=<\/tag>)/

基本上,我必须匹配<tag></tag> 之间的任何字符,并且需要保留这两个标签。我将此表达式用作 array.split 的参数。

输入: "The quick brown <tag>fox</tag> jumps over the lazy <tag>dog</tag>"

操作: input.split(regex)

输出: ["The quick brown ", "<tag>fox</tag>", " jumps over the lazy ", "<tag>dog</tag>"]

【问题讨论】:

    标签: javascript regex firefox regex-lookarounds


    【解决方案1】:

    firefox 和 safari 尚不支持lookbehind,您可以使用捕获组(这样我们正在拆分的模式也将添加到输出中)并在<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))

    【讨论】:

    • 它有效。我很欣赏你的回应。我意识到我过度设计了我最初的正则表达式。干杯
    • 在这种情况下不需要使用g修饰符,因为它是split的默认行为。
    【解决方案2】:

    也许,

    <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 可视化正则表达式:

    【讨论】:

    • 我试过这个并且它有效,但我觉得第一个答案更简单,足以满足实现要求。感谢您提供可视化!
    猜你喜欢
    • 2020-07-24
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 2015-01-24
    相关资源
    最近更新 更多