Visual Basic (3539)
About this site
Links to us
Using regular expressions (regexs) in Java
This article has not been rated yet. After reading, feel free to leave comments and rate it.
The java.util.regex package provides two classes for comparing a regular expression against an input String (actually against any CharSequence object2). A Pattern object is a compiled representation of a regular expression3. A Matcher object is an engine that performs match operations on a character sequence by interpreting a Pattern4. The Pattern class contains two static factory methods, compile(String) and compile(String, int), that create and return a Pattern object. The Pattern instance method matcher(CharSequence) creates and returns a Matcher object based on the Pattern instance and the input CharSequence.
Four methods are available to a Matcher object to match part or all of an input String against a regular expression pattern. From the Matcher class documentation4:
The boolean matches() method attempts to match the entire input sequence against the pattern.
The boolean lookingAt() method attempts to match part or all of the input sequence, starting at the beginning, against the pattern.
The boolean find() and boolean find(int) methods scan the input sequence looking for the next subsequence that matches the pattern.
Each of these methods will return true if the pattern matched part or all of the input String as appropriate. As a side effect, the find methods set internal state information in the Matcher object that is used to track the last location where a match occurred.
String input = "She sells sea shells by the sea shore.";
Pattern pattern = Pattern.compile("shells");
Matcher matcher = pattern.matcher(input);
String splits = pattern.split(input);
for (int i=0; i < splits.length; i++)
pattern = Pattern.compile("Shells");
matcher = pattern.matcher(input);