Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the complexity of regular expression?

What is the complexity with respect to the string length that takes to perform a regular expression comparison on a string?

like image 312
Ahmad Farid Avatar asked Dec 07 '10 15:12

Ahmad Farid


People also ask

What is the time complexity of regular expression?

Time Complexity of Regex is O(MxN).

Why is regex so complicated?

Regular expressions are dense. This makes them hard to read, but not in proportion to the information they carry. Certainly 100 characters of regular expression syntax is harder to read than 100 consecutive characters of ordinary prose or 100 characters of C code.

Is regular expression faster than loop?

Regex is faster for large string than an if (perhaps in a for loops) to check if anything matches your requirement.

What are all the limitations of using regular expressions?

Regexs can only parse regular grammers anything context-free and higher you need a stack (i.e. a real parser). That is their only real limitation, performance depends the particular implementation, but generally is slow even precompiled compared to a state machine.


1 Answers

The answer depends on what exactly you mean by "regular expressions." Classic regexes can be compiled into Deterministic Finite Automata that can match a string of length N in O(N) time. Certain extensions to the regex language change that for the worse.

You may find the following document of interest: Regular Expression Matching Can Be Simple And Fast.

like image 52
NPE Avatar answered Sep 19 '22 21:09

NPE