What is a regular expression? Who should use them? How do we use them? Where can we use them? When should we use them?
What is a regular expression?
A regular expression is a pattern. That's all. People see patterns every day in their daily life. They make assumptions based on them. Many times when they're gambling in a casino, the assumptions they make based on patterns lead them astray.
With regular expressions, humans get to define the patterns that computers will use to match bits of text. Let's look at an example:
var re = /ab+c/;
In this particular instance, the statement "var re" means that we're creating a new variable named "re", and the "= /ab+c/;" means that we're assigning the pattern "ab+c" to the variable.
Who should use them?
How do we use them?
Well, that right there is the rub. There are nearly as many Regular Expression "engines" as programming languages that use them. So your best bet is to consult the documentation for the language you're working in and reference to regular expressions.
Sorry. It just wont do to offer you a bunch of different examples in language A, B, and C, when tomorrow, there will be a D. Learn your implementation, and I promise that those details will be very near to the next langauge your client begs you to implement a CRUD app in.
To make your life easier, I'll make a list here of various languages' documentation on the subject:
- Java 8
- PHP supports Perl-compatible and POSIX-compatiable regular expressions.
Where can we use them?
The answer to that question is basically anywhere we need to match text while using a language that supports them. Next question.
When should we use them?
Well now, we've arrived! This is the real question, and why I saved the best for last.
You see, Regular Expressions are a lot like Perl, one of the languages that allow you to use Regular Expressions, in that they are for the most part "Write Once, Read Never".
There is a high probability that you will create a regular expression to match a pattern of text, let 6 months pass, and then forget everything about the implementation that you created.
There is an oft-repeated quote that says ".+".
Regular expressions, when written by experts, can lead to near elegant solutions to otherwise terrible problems. Matching email addresses, phone numbers, ZIP codes, basically any string of text or numbers, can become easily solveable in the moment.
The problem is how regular expressions age.
They age like cake, not like wine.