O'Reilly logo

Java 9 Regular Expressions by Anubhava Srivastava

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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?

    \d{2}|\d{4}

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

    ^[+-]?\d*\.?\d+$

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required