Why can regular expressions have an exponential running time?

前端 未结 2 522
闹比i
闹比i 2020-11-28 09:50

It is possible to write a Regex which needs in some cases exponential running time. Such an example is (aa|aa)*. If there is an input of an odd number of

2条回答
  •  一整个雨季
    2020-11-28 10:22

    Regular expressions conforming to this formal definition are computable in linear time, because they have corresponding finite automatas. They are built only from parentheses, alternative | (sometimes called sum), Kleene star * and concatenation.

    Extending regular expressions by adding, for example, backward references can lead even to NP-complete regular expressions. Here you can find an example of regular expression recognizing non-prime numbers.

    I guess that, such an extended implementation can have non-linear matching time even in simple cases.

    I made a quick experiment in Perl and your regular expression computes equally fast for odd and even number of 'a's.

提交回复
热议问题