If you suddenly need RegEx to solve a problem, it can be tempting to google a syntax list and start awkwardly crafting the pattern that will (hopefully) match whatever string you need. This can be time consuming, however, and it’s likely that your solution is not the most efficient or readable one. Furthermore, despite assumptions that you’d “never have to use RegEx again, anyway”, you may indeed need to use RegEx again.
For these reasons I feel it’s best to take a small amount of time, one weekend in my case (two weekends if you have a life), to properly learn the fundamentals of RegEx.
For maximum learning efficiency, follow the 6 steps below and you’ll be writing logical regular expressions in no time.
1. Start with RegexOne
RegexOne is particularly useful if you’re a complete novice or just don’t remember the syntax yet. It starts with very simple problems that become increasingly difficult. The good thing about this tutorial is that all the documentation is provided above the problem. Along side this you could also refer to Corey Schafer’s video which does a great job of introducing RegEx.
2. Find readable documentation
This answer on Stack Overflow addresses a general query about understanding RegEx. It explains, in a very readable way, what each syntax will match and why. Plenty of other reference sites exist – Regular-Expressions.info is another example. Remember to bookmark your preferred documentation for quick reference.
3. Discover RegEx Pal
RegEx Pal is a great tool that lets you enter your own text and regular expressions to see what matches. It’s a testing tool rather than a teaching tool, but knowing about it will make a lot of difference when it comes to solving your own pattern matching problems.
4. Test your new skills
Once you’ve acquired the basics, have a go at this RegEx game from the Machine Learning Lab. Don’t worry if you can’t complete every question, it’s a good way to practice matching varied strings in sample text. You can also come back to this page in the future and test your progress.
5. Regex Crossword
Start playing RegEx Crossword. It can be a little confusing at first so start with the tutorial and then the beginner puzzles. These ‘crosswords’ are a really good way to cement the syntax and concepts of RegEx into your memory. They’re also incredibly fun and addictive, so remember to take breaks from your computer if you find yourself in a crossword hole.
6. Practice
RegEx may not always be needed for your work or projects, and quite some time may pass between the moments when you rely on it. Practice it regularly in your own time to avoid having those ‘Oh god, how do I do this again?’ days. This is where RegEx Crossword comes in handy – you can do the puzzles on the train or during a coffee break.
Good Luck!
The above steps should get you well on your way to competent regexing. Good luck and happy learning!