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,}$/
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 (-)β οΈ This is the username before @
|
@ |
Matches the literal @ symbol |
[a-zA-Z]+ |
Matches one or more letters, uppercase or lowercase π This is the domain name like 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 | β
Built-in (RegExp ) |
Python | β
re module |
Java | β
java.util.regex
|
PHP | β
preg_match()
|
Ruby | β Native |
Go | β
regexp package |
Rust | β
regex crate |
Bash | β grep/sed/awk |
β οΈ 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.
Top comments (0)