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 ...

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.