YouTip LogoYouTip

Regex Quantifiers and Anchors

Introduction

Quantifiers control how many times a pattern must match. Anchors match positions rather than characters. Together, they provide precise control over regex matching.

Quantifiers

*             Zero or more times
+             One or more times
?             Zero or one time
{n}           Exactly n times
{n,m}         Between n and m times
{n,}          n or more times

# Examples
/a*/          matches "", "a", "aaa"
/a+/          matches "a", "aaa" (not "")
/d{3}/       matches exactly 3 digits
/d{2,4}/     matches 2, 3, or 4 digits

Anchors

^             Start of string/line
$             End of string/line
b            Word boundary
B            Non-word boundary

# Examples
/^Hello/      matches "Hello World"
/World$/      matches "Hello World"
/bwordb/    matches "word" as whole word

Greedy vs Lazy

# Greedy (default) - matches as much as possible
/<.+>/     matches "<div>hello</div>" (whole string)

# Lazy - matches as little as possible
/<.+?>/    matches "<div>" (first tag only)

# More lazy quantifiers
*?     Zero or more (lazy)
+?     One or more (lazy)
??     Zero or one (lazy)

Practical Examples

# Match complete lines
/^.*$/m

# Match whole words only
/bJavaScriptb/

# Match 2-5 word characters
/w{2,5}/

Summary

Quantifiers set repetition, anchors match positions. Use ^ and $ for string boundaries, and add ? to make quantifiers lazy.

← Regex Groups and CapturingRegex Character Classes β†’