DEV Community

Shakhzhakhan Maxudbek
Shakhzhakhan Maxudbek

Posted on • Originally published at args.tech

How to work with regular expressions

What are regular expressions? These are patterns that help us work with text. Regular expressions (regex, regexp) used to match sequences of characters in strings: search, edit, delete any area in large texts, data generation or validation, and so on. Regexes can be used in programming languages, command line interfaces, etc...

For example I want validate email addresses from my domain. The expression will look like this:

^.*\@example\.com$
Enter fullscreen mode Exit fullscreen mode

^ symbol means the beginning of an expression.
Next symbols .* need for matching any address in @example.com domain.
Backslash before "at" symbol need for validate @ as is. The same situation with \. symbols.
$ - end of expression.

Result:

Image description

Next case need for validation phone numbers. I need accept numbers only from my region. In my case numbers started from +77. I should use this expression:

^\+77\d{1,9}$
Enter fullscreen mode Exit fullscreen mode

^ symbol means the beginning of an expression.
\+ - using "plus" symbol as "plus" symbol.
\d - presents d as digits.
In curly brackets {1,9} digits length.
$ - end of expression.

Result:

Image description

Additionally maybe validation when phone number starts from "+77" or "87":

^(\+77|87).?\d{1,9}$
Enter fullscreen mode Exit fullscreen mode

(\+77|87).? - number starts from +77 or 87.

Result:

Image description

Now let's look at IP address validation. For verification IP addresses you may use this expression:

((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}
Enter fullscreen mode Exit fullscreen mode

Result:

Image description

Thanks for regex101.com site, which allowed test my regular expressions.

Top comments (0)