[每天一个知识点]10-Java语言-正则表达式使用

正则表达式是个非常常用的工具,尤其是用于匹配和替换的时候,几乎每个程序中都有机会用到,java支持的正则表达式语法见regular expression。我在代码中经常看到的用于匹配的写法是

Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();

或者

boolean b = Pattern.matches("a*b", "aaaaab");

这种复杂的写法,这也不知道是哪个培训学校教的。

实际上,用于匹配的时候可以直接使用String的matches方法

booleanmatches(String regex)

Tells whether or not this string matches the given regular expression.

用于替换的时候可以直接使用String的replaceAll和replaceFirst方法

StringreplaceAll(String regex, String replacement)

Replaces each substring of this string that matches the given regular expression with the given replacement.

StringreplaceFirst(String regex, String replacement)

Replaces the first substring of this string that matches the given regular expression with the given replacement.


转载于:https://my.oschina.net/u/1762727/blog/368939

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值