Regular Expressions in Java
Now that you have an idea of how regular expressions can be used to match patterns, this topic will focus on how regular expressions can be used within Java applications. To use regular expressions in Java, the java.util.regex
package is available. The two main classes there are called Pattern
and Matcher
.
The Pattern
class handles the actual pattern; it validates, compiles, and returns a Pattern
object that you can store and reuse multiple times. It can also be used to perform quick validations against a supplied string.
The Matcher
class allows us to extract more information, and to perform different kinds of matching on the supplied text.
Creating a Pattern
object is as simple as using the static compile
method.
For example, you would like to compile a pattern to ensure that a text contains at least one a
. Your Java code should be as follows:
Pattern pattern = Pattern.compile("a+"); Matcher matcher = pattern.matcher("How...