Quantifiers

Specify how many times to match

#quantifiers #repetition #patterns

Quantifiers

Quantifiers specify how many times a pattern should match.

Basic Quantifiers

*       Match 0 or more times
+       Match 1 or more times
?       Match 0 or 1 time (optional)
{n}     Match exactly n times
{n,}    Match n or more times
{n,m}   Match between n and m times

Examples

# Match one or more digits
\d+

# Match optional sign followed by digits
-?\d+

# Match 2-4 letters
[a-z]{2,4}

# Match postal code (5 or 9 digits)
\d{5}(-\d{4})?

# Match repeated word
\b(\w+)\s+\1\b

Greedy vs Lazy

# Greedy (match as much as possible)
<.+>      Matches: <b>bold</b><i>italic</i>

# Lazy (match as little as possible)
<.+?>     Matches: <b> and </b> separately

Discover another handy tool from EditPDF.pro