Java Reference
In-Depth Information
An extended version of the REDemo program presented in Using regexes in Java: Test for a
Pattern , called REDemo2 , provides a display of all the capture groups in a given regex; one ex-
ample is shown in Figure 4-3 .
Figure 4-3. REDemo2 in action
It is also possible to get the starting and ending indices and the length of the text that the pat-
tern matched (remember that terms with quantifiers, such as the \d+ in this example, can
match an arbitrary number of characters in the string). You can use these in conjunction with
the String.substring() methods as follows:
String patt = "Q[^u]\\d+\\." ;
Pattern r = Pattern . compile ( patt );
String line = "Order QT300. Now!" ;
Matcher m = r . matcher ( line );
iif ( m . find ()) {
System . out . println ( patt + " matches \"" +
line . substring ( m . start ( 0 ), m . end ( 0 )) +
"\" in \"" + line + "\"" );
} else
else {
System . out . println ( "NO MATCH" );
}
Suppose you need to extract several items from a string. If the input is:
Search WWH ::




Custom Search