by jmnicolas · 9y ago · 0 comments
Would you embed Brainfuck in your code ? Then why do you use regexes ?
For example, in Python, if I want to match "foo" followed by any number of "bar"s and/or "quux"s at the end of the string, I could write this:
if re.match(r"foo(bar|quux)*$", my_string):
...
...without going to the trouble writing a recursive-descent parser or state machine, your way would be something like this: def ends_with_foo_etc(s):
if s.endswith("foo"):
return True
after_last = len(s) - s[::-1].find("oof")
if after_last > len(s):
return False
good_tail = True
while good_tail and after_last < len(s):
if s[after_last:after_last + 3] == "bar":
after_last += 3
elif s[after_last:after_last + 4] == "quux":
after_last += 4
else:
good_tail = False
return good_tail
if ends_with_foo_etc(my_string):
...
That's both excessively terse -- for a really simple pattern -- almost certainly slower and, most importantly, brittle in that it couples your pattern to your implementation in a non-trivial way. If your pattern changes, you may have to completely rewrite your matching function.It's also worth noting that a typical regex API will do more than just match patterns; e.g., extracting subpatterns/groups, splitting, etc.
Since this is anchored to the right, we can look at this from right to left: it's any mixture, including empty, of "quux" or "bar" elements, preceded by "foo". From this, a very simple algorithm pops out:
while (string does not end with "foo") {
if (string ends with "quux")
chop off "quux" from end of string
else if (string ends with "bar")
chop off "bar" from end of string
else
return "no match"
}
return "match"Writing fewer lines of code to do the same job is usually a good idea, providing it remains understandable. Personally, I find the syntax of regular expressions pretty straightforward and a lot of languages even allow you write comments within them to make them even easier to follow.
To be sure to truly understand your regex I would need to do a lot of Googling and a lot of thinking.
Regexes are not KISS IMO.
That being said I'd be surprised to your open-coded version of simple regexes like /hatstand.*teakettle/ or /badgerbrush\s{12}/ was clearer than the regex, and it would almost certainly be dismally slow relative to a tuned regex implementation - unless you wrote a lot of one-off SIMD code.
Further, if given a bunch of different regexes to match simultaneously, your code would have to run them one by one.
Finally, quite frequently our customers/users are in a situation where they don't know what the regex is going to be, and they aren't going to let people inject arbitrary code into their applications.
So if anything I blame lack of good taste for regular expressions bad rep.