DEV Community

Tala Amm
Tala Amm

Posted on • Edited on

Regular Expressions (REGEX): A Quick Refresher

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]+$/
Enter fullscreen mode Exit fullscreen mode

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}$/
Enter fullscreen mode Exit fullscreen mode
  • 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,}$/
Enter fullscreen mode Exit fullscreen mode

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)