正则表达式是个非常常用的工具,尤其是用于匹配和替换的时候,几乎每个程序中都有机会用到,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方法
boolean | matches(String regex)
Tells whether or not this string matches the given
regular expression.
|
用于替换的时候可以直接使用String的replaceAll和replaceFirst方法
String | replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given
regular expression with the given replacement.
|
String | replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given
regular expression with the given replacement.
|