Examples using quantifiers

Let's look at few examples to understand these basic quantifiers better.

Which regex pattern should be used to match a two-digit year or a four-digit year?


Which regex pattern should be used to match a signed decimal number? The pattern should also match a signed integer number:


Here is the breakup of the preceding regex pattern:

  • The ^ and $ symbols are the start/end anchors
  • The [+-]? pattern makes either the + sign or the - sign (optional because of ?) at the start
  • The \d* pattern matches zero or more digits
  • The \.? pattern matches an optional dot (.) literally
  • The \d+ pattern matches one or more digits

The preceding regex will match all of these inputs:

  • .45
  • 123789
  • 5
  • 123.45

Get Java 9 Regular Expressions now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.