正则表达式需要很长时间才能完成 [英] Regex takes a long time to complete

查看:40
本文介绍了正则表达式需要很长时间才能完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想匹配这样的一行:

  • 行首
  • 多个'-'
  • 也许是空白(也许更多)
  • 至少一个字符
  • 也许还有更多字符和空白
  • 也许是空白(也许更多)
  • 多个'-'
  • 行尾

所以我这样写了正则表达式:

So I wrote the Regex like this:

new Regex(@"^\-{2,}\s*(\w+(\w+|\s)*)\s*\-{2,}$");

当我尝试匹配以下行时,这需要花一些时间才能完成(没有等待它完成):

And when I try to match the following line, this takes ages to complete (didn't wait for it to complete):

-------- Variable used for recipe visualization only - Not loaded into PLC --------

我认为其中有很多比赛,而Regex很难枚举所有这些比赛,但我不确定.

I think there's a very big number of matches in it and the Regex have hard time enumerating all those matches but I'm not sure.

环境信息:Windows 7,框架3.5

Environment information: Windows 7, framework 3.5

谢谢

在您的帮助下,我想出了一个可以运行的正则表达式:

Thanks to your help I came up with a Regex that works:

^-{2,}\s*(?!\-)(\w(?:\w|\s|\-)+)(?<!\-)\s*-{2,}$

所以解释:

  • 行首
  • 至少两个'-'
  • 也许是空白(也许更多)
  • 不再有'-'
  • 至少一个字符
  • 也许更多字符,空格或'-'
  • 不再有'-'
  • 也许是空白(也许更多)
  • 至少两个'-'
  • 行尾

如果您发现问题,请告诉我

If you see something wrong with it please tell me

推荐答案

将嵌套分组展开为

^-{2,}\s*(\w+(?:\s+\w+)*)\s*-{2,}$
             ^^^^^^^^^^^ 

否则,您的模式将易于灾难性的回溯.

Otherwise, your pattern will be prone to catastrophic backtracking.

请参见 regex演示

或者,使用原子组禁用到替代组的任何回溯:

Alternatively, use an atomic group to disable any backtracking into the alternation group:

^-{2,}\s*((?>\w+(?:\w+|\s)*))\s*-{2,}$
          ^^^              ^ 

请参见通常,请避免在较长的模式中使用嵌套量词(例如(\ w + | \ s)* 中的交替词)进行交替.

Generally, avoid alternations with nested quantifiers (like in (\w+|\s)*) inside longer patterns.

这篇关于正则表达式需要很长时间才能完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆