DEV Community

Cover image for Regex 101
Shreyas Pahune
Shreyas Pahune

Posted on • Edited on

Regex 101

Hey readers 👋🏻, in this blog we are going to talk about Regular Expressions or we can also call it REGEX .

REGEX is sequence of characters which are in a certain patter, and these patterns help us find or find and replace or validate things like email, passwords and usernames.

Let's start learning 🐱‍🏍:

 

Basics :

The most easy way to explain regex with an example is if:

we want to search the word JavaScript in a string.

first

Now this example is very basic but believe me REGEX has lots and lots of use-cases.

 

Multiple Possible Characters :

Let's see an example where you want to see if the string contains many possibilities for example if you want to search for dog or cat .

We can do this by using | the OR sign.

second

Here if the petString would contain Shreyas loves JavaScript then the output would have been false.

To be clear, the REGEX patterns are case sensitive, so if a string would contain shreyas and I search for ShreyaS then the output would be false.

 

Case Sensitiveness :

What should we do when we are not sure about the case... No worries! We can make our REGEX Pattern ignore the case.

three

As you can see we have used i in regex1, and there are many such flags which gives us a lot of control over the pattern.

i stands for irrespective of the case.

Here we are using .test() method, which is an inbuilt method in JavaScript, which returns true or false according to the pattern entered.

The Syntax is pattern.test(String-which-has-to-be-tested) .
 

Global Searching :

.test() has a draw back, which is that it only returns true or false, and if true it does not tell us how many times the pattern was matched, so to back this drawback, JS has another inbuilt method called as .match() which let's us know how many times the pattern is matched in the string.

.match() return an array of results which have successfully matched the pattern, and the array's length is the time the pattern was recognized.

Let me show an example 👇🏻:

four

Here you can see the syntax of .match() is a little bit different when compared to .test()

.match() 's syntax is : string.match(regex-pattern);

Also you can see that I have used another flag, which is g and it stands for global, which helps us find the perfect match globally in the string.

 

Find Group of Letters :

We can group many letters together to find them inside a string. REGEX gives us flexibility with Character Classes, these allow us to define a group of characters and they have to be enclosed in [ ] (Square Brackets) .

It will be more clear when you see an example.

We have to find every vowel inside a string. 👇🏻
five

The pattern has 2 flags, which are non case sensitive and to check globally in the string.

Here [aeiou] vowels are grouped together and are individually searched in the string.

 

Match anything using Wildcard period / dot :

Some times we just have to search for words which end with some certain letters or which start from some certain letters. To do so, we have wildcard period which is basically a . period/dot.

If we have to match words which end with the letters un . For example fun or run or sun .

For that we have 👇🏻

six

This pattern will check for any word ending with un and it will do it irrespective of the case(i flag) and would search in the whole string (g flag).

 

Range of Characters :

We can also provide a range of characters to check from.

seven

For Example: If you are sure that there are possibilities that the word may start with any character but the ending will be with the letters at , then we can give a range of characters which will check the string and if matched then return an array.

Note: If no value is found, NULL would be returned!

 

Match Numbers :

What if, you wanna match numbers?? Don't worry REGEX has got you covered!

Just like characters we can write /[0-9]/g, that's it, all the numbers are covered.

But as we all know, us developers...we are lazy 💤! So why to write /[0-9]/ when you can also write /[\d]/g and this d stands for digits!

 

Match Number and Characters :

To match number and characters, we can write 👇🏻

eight

But isn't this REGEX Pattern too long?? We have a shorthand for this, which is /\w/g and instead of the whole REGEX pattern you can just write the shorthand.

 

Check for Minimum and Maximum Characters :

We can set a min and a max amount of characters.

nine

This REGEX pattern allows only those strings which have equal or greater length then 5 and are under or equal to 10.

The syntax for that is /[regex here]{min-number, max-number}/g.


Challenge 🎯:

I wanna give a quick challenge to all the readers, why don't you make a REGEX which verifies usernames, and the conditions are:

  1. Username should have numbers.
  2. Username can have an underscore.
  3. Username should not have any special characters.
  4. Username should have minimum 5 characters and maximum 15 characters.

Thank you so much for reading the whole blog 🎉, if you liked it do share it with your friends and implement REGEX in your upcoming projects! It has saved me from writing lots of line of code and a lot of time too, I am sure it will be very effective for you too!

Till the next blog... Goodbye 👋🏻 !!

Top comments (8)

Collapse
 
valeriavg profile image
Valeria

One should be aware of Regular Expression Denial of Service attack when validating user input on the backend.
These seemingly simple regular expressions can cause infinite loops:

(a+)+
([a-zA-Z]+)*
(a|aa)+
(a|a?)+
(.*a){x} for x \> 10
Enter fullscreen mode Exit fullscreen mode
Collapse
 
shreyazz profile image
Shreyas Pahune

Thanks for the info 😇

Collapse
 
gktim profile image
gkTim

Nice Post. You should add or do a Part 2 with stuff like positive/negative lookahead and lookbehind

Collapse
 
shreyazz profile image
Shreyas Pahune

That’ll be included in part-2 cuz It is a lot to include in one blog! Thanks btw 🎉😄

Collapse
 
abhishe01794149 profile image
Abhishek Chandel

/([a-zA-Z]{1,5})/g.test('abhishek')

why is this giving true?

Collapse
 
shreyazz profile image
Shreyas Pahune

It is coming true cuz, it is only testing abhis because of the {1,5} clause, and that substring exists in your name abhishek.

Collapse
 
abhishe01794149 profile image
Abhishek Chandel

then this should give false - /([a-zA-Z]{1,5})/g.test('1abhishek'), but it is giving true again

Thread Thread
 
shreyazz profile image
Shreyas Pahune

Lemme try this on my end