M:多行模式
l 作用:更改 ^ 和 $ 的比對規定,它們可以比對字元串内部各行文本的開頭和結束位置
l \A 和 \Z 則不受影響
在講錨點的時候,說過, ^ 和$一般情況下,隻能能比對整個字元串的開頭和結尾位置。
看例子:
public class MultiLine {
public static void main(String[] args) {
String str = "<a href=www.sina.com.cn>\nSINA\n</a>";
String regex = "^SINA$";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
if(m.find()){
System.out.println(str + "能夠比對正則:" + regex);
}else{
System.out.println(str + "不能夠比對正則:" + regex);
}
運作結果:比對是否包含:SINA
<a href=www.sina.com.cn>
SINA
</a>不能夠比對正則:^SINA$
現在指定多行模式:
Pattern p = Pattern.compile(regex,Pattern.MULTILINE);
運作結果:
</a>能夠比對正則:^SINA$
說明:
MULTILINE
public static final int MULTILINE
Enables multiline mode.
In multiline mode the expressions ^ and $ match just after or just before, respectively, a line terminator or the end of the input sequence. By default these expressions only match at the beginning and the end of the entire input sequence.
Multiline mode can also be enabled via the embedded flag expression (?m).
See Also:
<a href="http://java.sun.com/javase/6/docs/api/constant-values.html#java.util.regex.Pattern.MULTILINE">Constant Field Values</a>
X: 注釋模式
l 作用:在正規表達式内部可以使用注釋
l 形式:注釋以 # 開頭,以換行符結束(或直到表達式的末尾)
l 使用此模式後,會忽略正規表達式中的所有空白字元
我們知道,如果正規表達式非常複雜,代碼閱讀者通常會被搞得一頭霧水。添加注釋,可以友善代碼閱讀者了解意圖。
例子:
public class CommentMode {
String str = "[email protected]";
String regex = "\\w+ #username\n" + "@" +"\\S+ #hostname";
Pattern p = Pattern.compile(regex,Pattern.COMMENTS);
[email protected]能夠比對正則:\w+ #username
@\S+ #hostname
COMMENTS
public static final int COMMENTS
Permits whitespace and comments in pattern.
In this mode, whitespace is ignored, and embedded comments starting with # are ignored until the end of a line.
Comments mode can also be enabled via the embedded flag expression (?x).
<a href="http://java.sun.com/javase/6/docs/api/constant-values.html#java.util.regex.Pattern.COMMENTS">Constant Field Values</a>
本文轉自jooben 51CTO部落格,原文連結:http://blog.51cto.com/jooben/321019