Java Reference
In-Depth Information
TryRegex.java
This produces the following output:
Pattern found at Start: 19 End: 22
Pattern found at Start: 23 End: 26
Pattern found at Start: 28 End: 31
Pattern found at Start: 34 End: 37
Pattern found at Start: 38 End: 41
Pattern found at Start: 43 End: 46
Pattern found at Start: 47 End: 50
Smith, where Jones had had 'had', had had 'had had'.
^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^
How It Works
You first define a string,
regEx
, containing the regular expression, and a string,
str
, that you search:
String regEx = "had";
String str = "Smith, where Jones had had 'had', had had 'had
had'.";
You also create an array,
marker
, of type
char[]
with the same number of elements as
str
, that you use
to indicate where the pattern is found in the string:
char[] marker = new char[str.length()];
You fill the elements of the
marker
array with spaces initially using the static
fill()
method from the
Arrays
class:
Arrays.fill(marker,' ');
Later you replace some of the spaces in the array with
'^'
to indicate where the pattern has been found
in the original string.
After compiling the regular expression
regEx
into a
Pattern
object,
pattern
, you create a
Matcher
ob-
ject,
m
, from
pattern
, which applies to the string
str
:
Pattern pattern = Pattern.compile(regEx);
Matcher m = pattern.matcher(str);
You then call the
find()
method for
m
in the
while
loop condition:
while( m.find() ){
System.out.println(
"Pattern found at Start: " + m.start() + " End: " +
m.end());
Arrays.fill(marker, m.start(), m.end(), '^');
}
This loop continues as long as the
find()
method returns
true
. On each iteration you output the index
values returned by the
start()
and
end()
methods, which reflect the index position where the first char-