Skip to main content
gamedev.net
🔒 Locked

Optimize my regular expression

Started by BeanDog 7 replies 750+ views
Original Post
BeanDog
BeanDog
Consider the following regex: (final)?\s*(abstract)?\s*(public|private|protected)?\s*(static)?\s*function\s*([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\(([^\)]*)\)(\s*;)? It is designed to find PHP function declarations. The problem is that it takes minutes to search 4KB of PHP source code. The problem is in the beginning. I'm looking for a sequence of possible modifiers (final, abstract, etc.) that may or may not appear before the function declaration. If I remove them from the regex entirely, it runs instantaneously. So, I've just removed them and manually searched for the modifiers after the simplified regex matched. It's a mess, though... Does anyone know how I could make this work reasonably quickly while still having the regular expression find the modifiers for me? Thanks!
BeanDog
BeanDog
The modifiers do in fact need to be in that order, according to the PHP documentation.
Zahlman
Zahlman
If you don't need to check what matched within the groupings (i.e. don't care whether or not the function actually is final or abstract etc.), you can use non-capturing groupings:

(?:final\s+)?(?:abstract\s+)?(?:(?:public|private|protected)\s+)?(?:static\s+)?function\s*
twanvl
twanvl
Does the function need to match only functions exactly? Or is it okay if it gives incorrect results for input that is not valid PHP code? If that is the case then you can simplify the regex to something like:
((final|abstract|public|private|protected|static)\s+)*
Wyrframe
Wyrframe
twanvl beat me to it; you don't need a regexp to match 'real' syntax, so long as your real error checking is elsewhere (which it is; in the actual scripting engine). Your editor can use a much simplified form of the syntax, unless you want to be able to specifically highlight syntax errors, in which case a regexp is far too weak and slow a tool; you want an iterative re-sequencable parser, which takes up more memory to store the reparsing tree, but gives updates near-linear on the input size, better if you break the parsing system into distinct lines of code.
RIP GameDev.net: launched 2 unusably-broken forum engines in as many years, and now has ceased operating as a forum at all, happy to remain naught but an advertising platform with an attached social media presense, headed by a staff who by their own admission have no idea what their userbase wants or expects.Here's to the good times; shame they exist in the past.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.