Wednesday, April 25, 2012

Java Regex Pattern and "^M"

A simple pattern:
 Pattern title = Pattern.compile("^Alert\\s*Digest.*", Pattern.CASE_INSENSITIVE);
When I tried to match this string. It failed:
Alert Digest No 6 of 2012^M 
 Yes, you can see that "^M" in the string. This is a "line terminator" which "." will not match by default.

So the solution is:
 Pattern title = Pattern.compile("^Alert\\s*Digest.*", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
 This is the description from API document:

DOTALL

public static final int DOTALL
Enables dotall mode. In dotall mode, the expression . matches any character, including a line terminator. By default this expression does not match line terminators.

 

No comments:

Post a Comment