Java Reference
In-Depth Information
characters it finds. If you read in gobs of characters using some method other than
readLine() , you may have some number of \n , \r , or \r\n sequences in your text string. [ 20 ]
Normally all of these are treated as equivalent to \n . If you want only \n to match, use the
UNIX_LINES flag to the Pattern.compile() method.
In Unix, ^ and $ are commonly used to match the beginning or end of a line, respectively. In
this API, the regex metacharacters \^ and $ ignore line terminators and only match at the be-
ginning and the end, respectively, of the entire string. However, if you pass the MULTILINE
flag into Pattern.compile() , these expressions match just after or just before, respectively,
a line terminator; $ also matches the very end of the string. Because the line ending is just an
ordinary character, you can match it with . or similar expressions, and, if you want to know
exactly where it is, \n or \r in the pattern match it as well. In other words, to this API, a
newline character is just another character with no special significance. See the sidebar Pat-
tern.compile() Flags . An example of newline matching is shown in Example 4-7 .
Example 4-7. NLMatch.java
public
public class
class NLMatch
NLMatch {
public
public static
static void
void main ( String [] argv ) {
String input = "I dream of engines\nmore engines, all day long" ;
System . out . println ( "INPUT: " + input );
System . out . println ();
String [] patt = {
"engines.more engines" ,
"ines\nmore" ,
"engines$"
};
for
for ( int
int i = 0 ; i < patt . length ; i ++) {
System . out . println ( "PATTERN " + patt [ i ]);
boolean
boolean found ;
Pattern p1l = Pattern . compile ( patt [ i ]);
found = p1l . matcher ( input ). find ();
System . out . println ( "DEFAULT match " + found );
Pattern pml = Pattern . compile ( patt [ i ],
Pattern . DOTALL | Pattern . MULTILINE );
found = pml . matcher ( input ). find ();
System . out . println ( "MultiLine match " + found );
System . out . println ();
 
Search WWH ::




Custom Search