正则表达式 学习笔记5.3

模式的混合: <?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

作用:同时使用多个模式

形式:在编译正则表达式时,把表示模式的多个参数以竖线“|”连接起来

例子:

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

模式的冲突:优先选择模式作用范围

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值