M:
多行模式
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
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 href=www.sina.com.cn>
SINA
</a>能够匹配正则:^SINA$
说明:
int java.util.regex.
Pattern
.MULTILINE = 8 [0x8]
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:
X: 注释模式
l
作用:在正则表达式内部可以使用注释
l
形式:注释以 # 开头,以换行符结束(或直到表达式的末尾)
l
使用此模式后,会忽略正则表达式中的所有空白字符
我们知道,如果正则表达式非常复杂,代码阅读者通常会被搞得一头雾水。添加注释,可以方便代码阅读者了解意图。
例子:
public
class
CommentMode {
public
static
void
main(String[] args) {
String str =
"happymaster@163.com"
;
String regex =
"\\w+ #username\n"
+
"@"
+
"\\S+ #hostname"
;
Pattern p = Pattern.
compile
(regex,Pattern.
COMMENTS
);
Matcher m = p.matcher(str);
if
(m.find()){
System.
out
.println(str +
"能够匹配正则:"
+ regex);
}
else
{
System.
out
.println(str +
"不能够匹配正则:"
+ regex);
}
}
}
运行结果:
happymaster@163.com能够匹配正则:\w+ #username
@\S+ #hostname
说明:
int java.util.regex.
Pattern
.COMMENTS = 4 [0x4]
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).
See Also: