Tutorial2024-04-07

Hello Friends! Let's Master Regular Expressions Together

Regular expressions don't have to be scary. In this step-by-step guide, we'll build regex patterns from scratch — with real examples you can use today.

#regex#tutorial#beginner#text-processing#javascript

Hello friends, welcome back to the blog! 🙏

Today we are learning regular expressions. Many people think regex is very difficult. But I tell you — it is not! After this article, you will write regex patterns confidently.

Let me start from the very beginning. No prior knowledge needed.

What Is a Regular Expression?

A regular expression (regex) is a pattern that matches text. That's it. You give it a string of text, and it tells you "yes, this matches" or "no, this doesn't match."

const pattern = /hello/;
pattern.test("hello world"); // true ✅
pattern.test("goodbye world"); // false ❌

Building Blocks

1. Literal Characters

The simplest regex is just text:

/cat/ matches "cat" in "the cat sat"

2. Character Classes

Match any ONE character from a set:

/[aeiou]/ matches any vowel
/[0-9]/ matches any digit
/[a-zA-Z]/ matches any letter

3. Quantifiers

How many times to match:

/a*/ — 0 or more 'a's
/a+/ — 1 or more 'a's
/a?/ — 0 or 1 'a'
/a{3}/ — exactly 3 'a's
/a{2,5}/ — between 2 and 5 'a's

4. Anchors

Where in the string to match:

/^hello/ — starts with "hello"
/world$/ — ends with "world"

Real-World Examples

Validate an Email

/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/

Let me break this down:

  • ^ — start of string
  • [a-zA-Z0-9._%+-]+ — one or more valid email characters
  • @ — the @ symbol
  • [a-zA-Z0-9.-]+ — domain name
  • \. — the dot
  • [a-zA-Z]{2,} — TLD (at least 2 letters)
  • $ — end of string

Validate a Phone Number

/^\+?[\d\s-]{10,15}$/

Extract URLs from Text

/https?:\/\/[^\s]+/g

Common Mistakes

  1. Greedy vs Lazy.* matches everything. Use .*? for lazy matching.
  2. Forgetting to escape. matches any character. Use \. for a literal dot.
  3. Not testing edge cases — Always test with empty strings, very long strings, and special characters.

Tools That Help

Don't write regex from memory. Use a Regex Generator to build patterns visually, and test them with a Regex Tester before putting them in production.

Practice Exercises

Try these patterns:

  1. Match a valid hex color code (#FF0000)
  2. Match a date in YYYY-MM-DD format
  3. Match a valid IP address (192.168.1.1)
  4. Extract all hashtags from a tweet

Build and test regex patterns visually with our free Regex Generator — real-time matching, explanation, and common pattern library.

🛠

Try It Yourself

Put what you've learned into practice with our free online tools.