4 ms·
<this is a repost, but I like to spread the good word when the opportunity avails itself> I think one reason why most people have a hard time reading regex is
by viggity 5y ago
<this is a repost, but I like to spread the good word when the opportunity avails itself>
I think one reason why most people have a hard time reading regex is because they don't use any indentation or linebreaks.
Honestly, if a buddy came to you and asked you to help him debug a javascript method and all 15 statements were on the same line, would you offer to help him, or tell him to fix his shit first so you can read it?
What if it was all on one line and his variable names were all "v1", "v2", etc. Would you help him then? fuck no. And yet, this is standard operating procedure with regex, except you don't even get "v1", "v2" because nothing is labeled at all. v1/v2/... would be an improvement!
This is how most people write a simple date regex:
\d{1,2}/\d{1,2}/(\d{4}|\d{2})
And mind you, this is a very simple scenario. Here is how you would write it if you treated it like actual code:
(?<month>\d{1,2})
/
(?<day>\d{1,2})
/
(?<year>\d{4}|\d{2})
First off, you can know what my intent is when I'm capturing each group. Maybe this code gets used by a european where the month and day switch places. They can figure out how to fix it in like two seconds. Secondly, the forward slashes are not lost in a sea of characters anymore because we use whitespace like a civilized developer, not a regex savage.
If you want to keep things simple with regular expressions:
* Be liberal with what your pattern matches and use a normal programming language for your complicated conditional logic to filter out crap you don't want
* Don't be afraid to break up the search with multiple regular expressions
* Ignore pattern whitespace and use it to visually break up your pattern. Nobody would agree to debug javascript that has been minimized, yet people do this all the time with regex
* For the love of all that is holy, USE NAMED GROUPS. It is a fantastic way to document your intent.
- nicoburns 5y agoPart of the reason for this is that many languages don’t support these features. For example JavaScript supports neither extra white space or named capture groups in it’s regarded.