Course contentsShow
← Java
Lesson 2292 of 2,87044. Regular ExpressionsFree lesson

Quantifiers: *, +, ?, and {n,m}

Learn the four main quantifier types: zero or more, one or more, optional, and exact or range repetition.

Quantifiers: *, +, ?, and {n,m}

You'll learn how to specify how many times a pattern element should repeat using the four essential regex quantifiers.

What Are Quantifiers?

Quantifiers tell the regex engine how many times the preceding character or group should appear. Think of them as multipliers: they let you match patterns like "three digits" or "one or more letters" without writing the same element repeatedly.

The Four Core Quantifiers

* (Zero or More)
Matches the preceding element 0 or more times. The pattern "a*" matches "", "a", "aa", "aaa", etc.

+ (One or More)
Matches the preceding element 1 or more times. The pattern "a+" matches "a", "aa", "aaa", but not an empty string.

? (Zero or One / Optional)
Makes the preceding element optional—it can appear 0 or 1 time. The pattern "colou?r" matches both "color" and "colour".

{n,m} (Range)
Matches between n and m repetitions:

  • {3} — exactly 3 times
  • {2,5} — between 2 and 5 times
  • {3,} — 3 or more times

Practical Example

Pattern digits = Pattern.compile("\\d+");          // one or more digits
Pattern optionalSign = Pattern.compile("-?\\d+");  // optional minus sign
Pattern zipCode = Pattern.compile("\\d{5}");       // exactly 5 digits
Pattern phone = Pattern.compile("\\d{3}-\\d{3}-\\d{4}"); // 555-123-4567

These quantifiers apply to whatever comes immediately before them—a single character, a character class like \\d, or a group like (abc)+.

Key Takeaway: Use * for zero-or-more, + for one-or-more, ? for optional, and {n,m} for precise repetition counts to control how many times pattern elements repeat.