为什么这个正则表达式需要这么长时间才能执行

Why does this regex take so long to execute?

本文关键字:长时间 执行 正则表达式 为什么      更新时间:2023-09-26

我创建了regex,它应该移动相邻<span>标签的文本。

const fix = (string) => string.replace(/(['S]+)*<span([^<]+)*>(.*?)<'/span>(['S]+)*/g, "<span$2>$1$3$4</span>")
fix('<p>Given <span class="label">Butter</span>&#39;s game, the tree counts as more than one input.</p>')
// Results in:
'<p>Given <span class="label">Butter&#39;s</span> game, the tree counts as more than one input.</p>'

但是,如果我向它传递一个字符串,其中没有文本接触<span>标签,则需要几秒钟才能运行。

我正在ChromeElectron上对此进行测试.

(['S]+)*([^<]+)*是导致灾难性回溯的罪魁祸首,当没有</span>时。您需要将正则表达式修改为

(['S]*)<span([^<]*)>(.*?)<'/span>(['S]*)

它会起作用,但仍然没有效率。

为什么使用字符类进行'S?以上简化为

('S*)<span([^<]*)>(.*?)<'/span>('S*)

如果您只关心span的内容,请改用它

<span([^<]*)>(.*?)<'/span>

在这里检查 <= (请参阅步骤数的减少)

注意:最后不要用正则表达式解析 HTML,如果有工具可以更容易地做到这一点