模式的混合:
作用:同时使用多个模式
形式:在编译正则表达式时,把表示模式的多个参数以竖线“|”连接起来
例子:
public class MixedMode {
public static void main(String[] args) {
String str = "<a href=www.sina.com.cn>\nSINA\n</a>";
String regex = "<a href.*</a>";
Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher m = p.matcher(str);
if(m.find()){
System.out.println(str + "能够匹配正则:" + regex);
}else{
System.out.println(str + "不能够匹配正则:" + regex);
}
}
}
运行结果:
<a href=www.sina.com.cn>
SINA
</a>能够匹配正则:<a href.*</a>
模式的作用范围:
作用:精确控制各个模式的作用范围
形式:在表达式中,以 (?ismx) 的方式启用模式,以 (?-ismx) 的方式停用模式
我们知道,正则表达式一旦指定某个模式,则整个正则表达式都受这个模式的影响。
例子:
public class ModeSpanBasic {
public static void main(String[] args) {
String str = "abc";
String regex = "(?i)ABC";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
if(m.find()){
System.out.println(str + "能够匹配正则:" + regex);
}else{
System.out.println(str + "不能够匹配正则:" + regex);
}
}
}
运行结果:
abc能够匹配正则:(?i)ABC
不区分大小写,整个正则表达式。
某个位置停用不区分大小写的匹配:
String regex = "(?i)AB(?-i)C";
运行结果:abc不能够匹配正则:(?i)AB(?-i)C
下面看看多个模式作用范围:
public class MixedMode {
public static void main(String[] args) {
String str = "<a href=www.sina.com.cn>\nSINA\n</a>";
String regex = "(?is)<a href.*</a>";
Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher m = p.matcher(str);
if(m.find()){
System.out.println(str + "能够匹配正则:" + regex);
}else{
System.out.println(str + "不能够匹配正则:" + regex);
}
}
}
运行结果:
<a href=www.sina.com.cn>
SINA
</a>能够匹配正则:(?is)<a href.*</a>
模式的冲突:
如果在正则表达式内部,通过模式作用范围指定了模式,而在外部又指定了其他模式参数,则模式作用范围的优先级更高。
例子:
public class ModeConfict {
public static void main(String[] args) {
String str = "abc";
String regex = "(?-i)ABC";
Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
if(m.find()){
System.out.println(str + "能够匹配正则:" + regex);
}else{
System.out.println(str + "不能够匹配正则:" + regex);
}
}
}
运行结果:
abc不能够匹配正则:(?-i)ABC
小结:
匹配模式:改变某些结构的匹配规定
·I: 不区分大小写匹配
·S: 单行模式(点号通配模式)
·M: 多行模式
·X: 注释模式
模式作用范围:精确控制模式的作用范围
· (?ismx
· (?-ismx
模式的冲突:优先选择模式作用范围