How to use regular expressions in java?

Regular expressions are a powerful mechanism for string manipulation. Here, we won't be considering regular expressions in general, but will focus on their usage in Java. It is facilitated by the java.util.regex package from the standard library.

Working with regular expressions in Java starts with the Pattern class. This class represents the expression itself, independent of any target text. It can be created by compiling a string using the factory method Pattern.compile(). Patterns are immutable and thread-safe.

Matcher is a regular expression applied to specific text. It is produced by calling the method Pattern.matches(). A single pattern can generate multiple different matchers. Unlike patterns, a matcher is mutable and not safe for use in a multi-threaded environment. The primary operations of regular expressions — iterating over matches, accessing groups, and replacing — are implemented in this class.

Working with a Matcher instance resembles working with an iterator. The result of the matches() method will simply indicate whether the string matches the pattern. However, after this method is called, the matcher changes its state. You can now extract groups, find the match position in the text, and perform replacements.

There are several shortcut methods in Pattern for using a Matcher implicitly. For example, to simply check if a string matches an expression, you can use the single method Pattern.matches().