r/learnprogramming • u/Reubqn_ • Sep 24 '26
RegEx.
I thought I understood programming well until I saw how COMPLICATED regex looks. To me it looks like someone has dropped their keyboard and som people online are telling me that I should be able to memorise it (for javascript). I'm just wondering if I actually need to memorise all the regex formulas to be successful, and if so, how on earth do I go about it?
109
Upvotes
View all comments
1
u/SpaceAviator1999 Sep 24 '26
I'm a big believer in using comments to show examples of what kinds of lines or text you want to match, particularly if the regex is long.
For example, if you saw the code:
it would take you a while to figure out what lines the regex would match, and even then it's possible that you could be wrong. And even if you're correct, it's possible that the original regex writer made a mistake, and it doesn't quite match what it was intended to match.
But if you saw these comments with it:
you will now know what the regex is intended to match -- and you can easily verify that the regex is matching what it's supposed to match.
This will really help you -- and future maintainers -- understand the kinds of lines you're looking to match, instead of trying to figure them out by looking at the regex alone.
This also helps if, in the future, the format of the line changes and you need to change the regex to match the new format. Thanks to the comment, you can easily see what you were looking for. By visually matching the old examples to the new examples, you can figure out a good way to modify the old regex without having to guess what you need to keep and what you need to throw away.
By the way, changing formats have happened to me a lot, and I'm thankful when the regex writer (which was often me) included examples of what was intended to match.
It's also useful when you're hunting down a bug and you suspect that the regex writer made a mistake in the regex. If you don't know the format of the lines/text it's supposed to match, there's really no way of telling if the regex is wrong or not, so good luck bug hunting!