dev-resources.site
for different kinds of informations.
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$
^
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:
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}$
^
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:
Additionally maybe validation when phone number starts from "+77" or "87":
^(\+77|87).?\d{1,9}$
(\+77|87).?
- number starts from +77
or 87
.
Result:
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}
Result:
Thanks for regex101.com site, which allowed test my regular expressions.
Are my posts is helpful? You may support me on Patreon.
Featured ones: