This content originally appeared on DEV Community and was authored by Tala Amm
If you’ve ever wanted to find, match, or validate patterns in text, phone numbers, passwords, etc.; then regular expressions are your best friend.
What is a Regular Expression?
A regular expression, or regex, is a powerful pattern-matching language used to search, extract, or validate text based on specific patterns.
Think of it like a supercharged Ctrl+F
, but smarter.
Why Use Regex?
- Validate emails, phone numbers, passwords, URLs
- Search or replace specific text patterns
- Clean or extract data from messy text
- Apply rules flexibly in a single line
What Does a Regex Look Like?
Here’s a simple one:
/^[A-Z][a-z]+$/
Breakdown:
-
^
→ Start of string -
[A-Z]
→ One uppercase letter -
[a-z]+
→ One or more lowercase letters -
$
→ End of string
Matches:
John
, Alice
Doesn’t match:
john
, ALICE
, 123
Common Regex Symbols
Symbol | Meaning |
---|---|
. |
Any character except newline |
* |
Zero or more of previous item |
+ |
One or more |
? |
Zero or one |
\d |
Any digit (0–9) |
\w |
Any word character (a-z, A-Z, 0-9, _) |
[] |
Match one of characters inside |
() |
Grouping |
^ / $
|
Start / end of string |
Examples
Match a phone number (IL mobile):
/^(\+972|00972|0)5[02345689]\d{7}$/
- The string shall start with (+972 OR 00972 OR 0) followed by a 5 then one of these numbers [02345689] then have any 7 digits.
- Supports local (
05X...
) and international formats (+9725X...
) - Validates mobile prefixes like
050
,052
,054
, etc.
Match an email:
/^[\w.-]+@[a-zA-Z]+\.[a-zA-Z]{2,}$/
Of course, Tala! Let’s break down this regular expression step-by-step:
Breakdown:
Part | Meaning |
---|---|
^ |
Anchors the match to the start of the string |
[\w.-]+ |
Matches one or more characters that are: – \w : word characters (letters, digits, underscore)– . : dot (.)– - : dash (-)![]() @
|
@ |
Matches the literal @ symbol |
[a-zA-Z]+ |
Matches one or more letters, uppercase or lowercase![]() gmail , yahoo , etc. |
\. |
Escaped dot, because . means “any character” in regex.Here we want a literal dot, like in .com or .org
|
[a-zA-Z]{2,} |
Matches 2 or more letters for the domain extension like:com , net , io , co , etc. |
$ |
Anchors the match to the end of the string |
Example Matches:
tala.dev@gmail.com
example-world_123@dev.to.org
a@b.co
Which Languages Support Regex?
Regex is supported in almost every major programming language:
Language | Regex Support |
---|---|
JavaScript | ![]() RegExp ) |
Python | ![]() re module |
Java | ![]() java.util.regex
|
PHP | ![]() preg_match()
|
Ruby | ![]() |
Go | ![]() regexp package |
Rust | ![]() regex crate |
Bash | ![]() |
Gotchas
- Regex can be powerful, but hard to read.
- Overuse can reduce code readability.
- Always test your regex with tools like regex101.com or RegExr.
This content originally appeared on DEV Community and was authored by Tala Amm