Introduction to Regular Expressions
Regular Expressions, rexex, regexp. These words are nightmares of many programmers. For Computer Science students they're even worse. However some people love them. Seriously! There are many reasons for that.
What are regular expressions? They have been made to define text patterns. You may read proper theoritical introduction in [Wikipedia]. We won't do it here. Let's come straight to the funny part instead!
All the examples are made in [Expressions] app. Yes, that's our product and we're making content marketing here. But you don't have to buy it. There are plenty not-so-beautiful but free apps to play with regex. The article is free anyway!
Regular Expressions are fun
Just look at them! They're so beautiful. These brackets, asterisks, pluses and backslashes. Not convinced? Let's take a look at data parsing example.
Imagine you need to find any dates in the given text. You can make simple parser, of course. It will take some time and some code to write. Eventually, it should work quite well. But you might do it in a much simpler way.
For start let's assume that all dates are written as yyyy-mm-dd. Finding such dates using regular expressions is super easy. Just use this pattern: \d{4}-\d{2}-\d{2}. Simple! As you can guess \d is for a number and {n} tells how many characters should it consist of. Of course, you might write the parser manually.
If you like.
More fun
Let's go back to the date format. In first example we assumed that it's yyyy-mm-dd. What if date will be written as dd.mm.yyyy? Fortunatelly, we have regular expressions. That will be: (\d{4}-\d{2}-\d{2})|(\d{2}\.\d{2}\.\d{4}). Simple, again. If you're familiar with C-like language you will guess that | works like logical OR operator. Indeed, it will find date in any of these two formats. To make it clear, we had to use brackets. But what about \.? In Regular Expressions world . means any character. So we can't use it just like that. It must be escaped. That's why just before the dot stands a backslash \\. It tells that the next character must be treated as a regular character.
What if I don't write 0 before single-digit?
That might happen. You have right to do so. I'm not judging! Well, it's still quite simple: (\d{1,4}-\d{1,2}-\d{1,2})|(\d{1,2}\.\d{1,2}\.\d{1,4}).
{...} operator may take a number of a range of numbers. If you write {1,4}, it means that the previous expression must be at least 1 character long and not longer than 4 characters.
What's next?
That should be enough for start.
...
...
Expressions App
Yes, we made app for it. So it's must-be for us to write about it.
