天天看点

正则表达式 学习笔记5.2

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

下一篇: 邮箱伪造

继续阅读