DEV Community


Discussion on: Regex isn't that hard

pentacular profile image

Regex can be useful, but can also be a trap.

When you use regex, be sure to use just enough abstraction that you can swap out the regex implementation with a parser later on.

There are three main traps with regex:

  1. Regex do not handle recursive structures.
  2. Regex do not handle irregular languages.
  3. Regex scale rapidly to become impossible for a human to understand.

It is quite difficult to predict when you'll hit one of these limits, so a little abstraction goes a long way.

Instead of putting regex directly in your code, abstract them with a procedure that does something: e.g., getName(foo) instead of (foo.match(/([^/]+)/) || [])[1]; :)