java 正则表达式pattern类Matcher类

Pattern类:
例子:
Pattern pattern = Pattern.compile("[,\\s]+");
String[] result = pattern.split("one two three,four,five, six");
for(int i = 0; i<result.length; i++){
System.out.println(result[i]);
}
输出结果是:
one
two
three
four
five
six
Pattern类的静态方法compile用来编译正则表达式,在此[,\\s]+表示若干个","或者若干个空格匹配
split方法使用正则匹配将字符串切割成各子串并且返回

Matcher类:
注意,Matcher的获得是通过Pattern.matcher(CharSequence charSequence);输入必须是实现了CharSequence接口的类
常用方法:
matches()判断整个输入串是否匹配,整个匹配则返回true
例如下面会输出true
String str1 = "hello";
Pattern pattern1 = Pattern.compile("hello");
Matcher matcher1 = pattern1.matcher(str1);
System.out.println(matcher1.matches());

lookingAt()从头开始寻找,找到匹配则返回true
例如下面会输出true
String str2 = "hello yangfan!";
Pattern pattern2 = Pattern.compile("hello");
Matcher matcher2 = pattern2.matcher(str2);
System.out.println(matcher2.lookingAt());

find()扫描输入串,寻找下一个匹配子串,存在则返回true
例如下面将会将所有no替换成yes
Pattern pattern = Pattern.compile("no");
Matcher matcher = pattern.matcher("Does jianyue love yangfan? no;" +
"Does jianyue love yangfan? no;Does jianyue love yangfan? no;");
StringBuffer sb = new StringBuffer();
boolean find = matcher.find();
while(find){
matcher.appendReplacement(sb, "yes");
find = matcher.find();
}
matcher.appendTail(sb);
System.out.println(sb.toString());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值