What is RegEx?
A RegEx is a text that allows you to create patterns that help search, replace, and manage text. RegEx is shorthand for Regular Expressions.
Life without RegEx
You might be wondering why you should learn RegEx. After all, you can already search and replace without learning a new tool. So let’s discuss why you should invest your time in RegEx!
Scenario 1
Suppose you work for a big multinational company (MNC). Your manager gives you a 20-page long text document containing thousands of email records and asks you to locate every email with xyz.com
as their domain. Going about this task manually could take days! This is where RegEx comes in.
Let’s re-imagine the scenarios using the RegEx tool. To locate the emails with the xyz.com
domain, simply write the RegEx /.*?@xyz\.com/
. This will automatically search each email for matches to your input, so you don’t have to
Scenario 2
Let’s look at another example. Suppose you are a scientist working with DNA, and your boss provides you with very long strings of DNA that contain ATCG. Your boss then asks you to count the number of times pattern X occurs how many times pattern X occurs in a single DNA string. Manually matching each character one by one would be very tedious work.
RegEx allows you to feed and input , like X, and receive an output of all elements that match that input. This trait would make RegEx the ideal solution to high scale problems like this.
Why RegEx?
RegEx is a great tool to search a large dataset with minimal manual work required.
For example, if you were to manually search for phone numbers in a 20 page text that includes information other than phone numbers, you’d be searching for a long time. Using RegEx, we can complete this task with a couple of characters.
To find (234)-562-163, the pattern would be /[(]\d{3}[)](-\d{3}){2}/
. Any record that does not start with “(”, or contains more than three digits, or does not have a hyphen will not match.
Usage of RegEx
- Email and Password validation.
- Find all occurrences of “apple” and “Apple.”
- Parsing user input.
- Examining web server logs and many more.
A small challenge to showcase the need for RegEx
Find all the emails which have xyz.com
as their domain and write the integer answer next to the return statement.
var count = function(){let str = 'abc@xyz.com''bdvih@xyz.comp''bdadih@xyz.omp''vih@xyz.comp''dadihxyz.omp''bdvhxyzcomp''adh@x.omp''vih@xyz.com''bdih@yz.com'// e.g. return 10;return ;}
Solution for the above challenge
The two emails are ‘abc@xyz.com’ and ‘vih@xyz.com’
Note: In this course, JavaScript is used for code and quizzes. However, You can choose any language that you’re familiar with.The basic principles remain the same and intact everywhere.For every challenge, write the output and then press the run button. Otherwise, code widgets will generate the error.
In JavaScript RegEx is written inside /RegEx/flag
, and where str
denotes text in which RegEx needs to be applied str.match(/RegEx/flag)