本文共 2044 字,大约阅读时间需要 6 分钟。
M:多行模式
l 作用:更改 ^ 和 $ 的匹配规定,它们可以匹配字符串内部各行文本的开头和结束位置 在讲锚点的时候,说过, ^ 和$一般情况下,只能能匹配整个字符串的开头和结尾位置。 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); System. out .println(str + "能够匹配正则:" + regex); System. out .println(str + "不能够匹配正则:" + regex); Pattern p = Pattern. compile (regex,Pattern. MULTILINE ); int java.util.regex. .MULTILINE = 8 [0x8] public static final int MULTILINE 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). 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); System. out .println(str + "能够匹配正则:" + regex); System. out .println(str + "不能够匹配正则:" + regex); happymaster@163.com能够匹配正则:\w+ #username int java.util.regex. .COMMENTS = 4 [0x4] 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). 本文转自jooben 51CTO博客,原文链接:http://blog.51cto.com/jooben/321019 转载地址:http://jfbzo.baihongyu.com/