by jjice · 6y ago · 0 comments
A normal regex with a comment above it explaining what it does (for complex cases) always worked well for me.
And even if you know regex by heart - assembling it with function calls can still be better / safer just like you shouldn't insert SQL parameters by hand into your SQL query strings.
One problem is that I'm more likely to need regex almost anywhere but Java code.
We see this as early as in code review and as late as when you find a production bug because expectations of the surrounding code have changed.
For those reasons, we usually break regexes into parts anyway, and name and comment the single parts. Using the library's example, we might have:
protocol = "^(?:http)(?:s)?"
protocol_separator = "(?:\:\/\/)"
url = "(?:www\.)?(?:[^\ ]*)$"
regex = protocol + protocol_separator + url
Which turns out to be in the direction of these Java Verbal Expressions. I find the Verbal Expressions idea really enlightening.