- 前言
有这样一个小需求就是写一个方法,实现从原始字符串中删除与某个字串相匹配的所有子字符串,比如在
" hello world,I know you father,you know?"
删除 "you"后的结果为" hello world,I know father, know?"
,代码如下:
public class Client{
public static String remove(String source,String sub){
return source.replaceAll(sub,"");
}
public static void main(String[] args) throws Exception{
System.out.println(remove("你很好很好","好").equals("你很很"));
System.out.println(remove("$200.00","$").equals("200.00"));
}
}
** 运行结果:**
true
false
刚开始看不知道为什么,看了java里面的replaceAll这个源码才知道原来replaceAll的第1个参数是表示正则表达式,
/ * @param regex
* the regular expression to which this string is to be
matched
* @param replacement
* the string to be substituted for each match
*
* @return The resulting {@code String}
*
* @throws PatternSyntaxException
* if the regular expression's syntax is invalid
*
* @see java.util.regex.Pattern
*
* @since 1.4
* @spec JSR-51
*/
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
这就难怪了,在正则表达式里面$
表示结尾的意思。所以第二个输出返回结果肯定为false了。
那么我们如何解决这个问题呢?
其实我们可以使用replace
方法代替replaceAll
。
public String replace(CharSequence target, CharSequence replacement)
解决方案:将replaceAll改为replace
public static String remove(String source,String sub){
return source.replace(sub,"");
}
总结:使用String的replaceAll方法时要注意这个方法的第一个参数时表示正则表达式。