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 the Pattern class

Let's look at a few examples to understand some of these methods.

To compile a regular expression for decimal numbers, we can use the following code snippet:

final String decimalPattern = "^[+-]?\\d*\\.?\\d+$"; Final Pattern pattern = Pattern.compile(decimalPattern); 

The static method, Pattern.compile, compiles a string regex and returns a Pattern instance.

To match text between ## and ## that may include newlines as well, we can use the following compiled pattern:

final String re = "##.*?##"; Final Pattern pattern = Pattern.compile(re, Pattern.DOTALL); 

Here, we are using two parameters: the Pattern.compile method and passing DOTALL as a flag in the second parameter, since we want to match the newline ...

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