java之正则表达式

正则表达式用于匹配我们希望得到的内容,比如希望知道输入的字符串是否符合某个格式,同时希望得到匹配到的字符串。

匹配是否符合正则表达式要求的格式

栗子:判断输入字符串是否为’abc’

String htmlRegex = "abc";
String html = "abc";
boolean htmlMatched = html.matches (htmlRegex);
System.out.println (htmlMatched); //true

如果想知道 是否包含abc,

String htmlRegex = ".*abc.*";
String html = "aaaabcaaaa";
boolean htmlMatched = html.matches (htmlRegex);
System.out.println (htmlMatched); //true

这段代码 regex中的 . 代表匹配任意字符,* 代表0个或多个字符,表示贪婪

如果希望匹配 abc 前面有有限个字符的话

String htmlRegex = ".{3}abc.*";
String html = "aaaabcaaaa";
boolean htmlMatched = html.matches (htmlRegex);
System.out.println (htmlMatched); //true

如何希望获取匹配到的子字符串,那么需要用到java工具包里的Pattern和Matcher

Pattern Matcher
之前介绍了String的match 返回一个布尔值,主要表示目标字符串是否符合正则表达式的规则。
java还有一个Pattern用来构造一个regex表达式,其macher方法,用来执行匹配,返回一个Matcher对象,与String match不同的是,只要包含符合正则规则的字符串,则返回true,并把匹配到的子字符串放入group中。
Matcher实现了MatchResult接口:

start表示匹配到的字符串起始index
end表示匹配到的字符串结束index
group返回匹配到的字符串值
举个栗子:

Pattern p = Pattern.compile ("a{3}abc.*");
Matcher m = p.matcher ("llllllllllaaaabcaaaa");
// 是否包含满足 正则表达式的 字符串 
boolean flag = m.find (); //true
System.out.println (flag);
// 获得 满足正则表达式的 字符串
String matchResult = m.group (); //aaaabcaaaa
System.out.println (matchResult);

栗子2
获取html中以www开头com结束的字符串

Pattern p = Pattern.compile ("www.*?.com");
Matcher m = p.matcher ("<h1>this is test www.baidu.com.com </h1>");
// 是否包含满足 正则表达式的 字符串
boolean flag = m.find (); //true
System.out.println (flag);
// 获得 满足正则表达式的 字符串
String matchResult = m.group (); //www.baidu.com
System.out.println (matchResult);

参考资料:
正则表达式有以下规则:

非打印字符

特殊字符

限定符

定位符


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值