Developer

Regular Expressions for Beginners: Learn Regex with Examples

25 de octubre de 20257 min Leer
Regular Expressions for Beginners: Learn Regex with Examples

What Are Regular Expressions?

Regular expressions (regex) are patterns that describe text. They're used for searching, matching, and manipulating strings in virtually every programming language.

Basic Building Blocks

PatternMatchesExample
.Any characterc.t → cat, cut, c9t
\dAny digit\d\d → 42, 99, 01
\wWord character\w+ → hello, abc123
\sWhitespace\s → space, tab, newline
^Start of string^Hello → "Hello world"
$End of stringworld$ → "Hello world"
### Quantifiers
PatternMeaningExample
0 or moreabc → ac, abc, abbc
+1 or moreab+c → abc, abbc
?0 or 1colou?r → color, colour
{3}Exactly 3\d{3} → 123, 456
{2,4}Between 2 and 4\d{2,4} → 12, 123, 1234
### Practical Examples Email validation:
^[\w.-]+@[\w.-]+\.\w{2,}$
Phone number (US):
^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$
URL:
https?://[\w.-]+(/[\w.-])
Hex color code:
^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$

Groups and Alternatives

  • (abc) — capturing group
  • (?:abc) — non-capturing group
  • a|b — matches a OR b
  • [abc] — character class: a, b, or c
  • [^abc] — NOT a, b, or c
  • [a-z] — range: any lowercase letter

Testing Your Regex

The Regex Tester tool lets you:

  • Write regex patterns with instant feedback
  • See all matches highlighted in your test text
  • Understand what each part of your pattern does
  • Test edge cases before using in production

Common Mistakes

  • Forgetting to escape special characters., *, ?, (, ) have special meaning
  • Greedy matching. grabs as much as possible; use .? for lazy matching
  • Not anchoring patterns — without ^ and $, patterns match anywhere in the string
  • Over-complex patterns — if your regex is unreadable, split it into multiple simpler checks
  • regex
    regular expressions
    developer
    pattern matching

    Compartir este artículo