DEV Community

Shakhzhakhan Maxudbek
Shakhzhakhan Maxudbek

Posted on • Edited 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.


Are my posts is helpful? You may support me on Patreon.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay