jdk中String对象的replace和replaceAll方法

来源:互联网 发布:c 并发编程 书籍 编辑:程序博客网 时间:2024/06/05 08:24
java作为目前最受开发者欢迎以及热度最高的一门语言,在很多方面展现出了其特性,虽然灵活性不比c++,执行效率不比c,开发效率不比Ruby,但是作为最早最纯粹的OO语言,java在目前来说因为其在编程方面有着与c及c++语言的延续性而被广泛的使用。
即使java是如此的受欢迎,个人觉得jdk的api在很多方面却做的不是太好,简单的以命名来说。比如说string类的两个方法replace和replaceAll,因为有replaceAll的存在根据命名来看很容易使人觉得第一个replace方法是用replacement字串替换source字串中第一个出现的target字符串,而replaceAll方法是替换在source字串中所出现的所有target字串。

至少在jdk中它们是这样声明的:
public String replaceAll(String regex, String replacement) {...}

public String replace(CharSequence target, CharSequence replacement){...}

如果不去阅读它们的注释或者查看具体实现,你自然的觉得它们二者就只是存在着替换数量之间的差别,一个是全部替换,另外一个只是替换第一个(至少我是这样理解的,并且在此api上面也吃过一些亏)。

二者的注释分别为:
replaceAll 
Replaces each substring of this string that matches the givenregular expression with the given replacement.

replace
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. 
The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".

到此才得知replaceAll是采用正则表达式进行文本的替换,替换所有满足条件的substring。
replace是采用文本本身的内容进行匹配替换,也是所有满足条件的substring。

例如下面的代码:
                String info = "catfish+foolishcat";String withReplace = info.replace("catfish+", "rxr");String withReplaceAll = info.replaceAll("catfish+", "rxr");System.out.println("withReplace    is " + withReplace);System.out.println("withReplaceAll is " + withReplaceAll);
最后的输出分别为:
withReplace    is rxrfoolishcat
withReplaceAll is rxr+foolishcat

所以这两个方法在命名上面给开发者的歧义性太大,不具备可读性,至少不能望文生义,replace替换成replaceWithLiteralTarget,replaceAll替换成replaceWithRegexTarget能够从语义上面区分出二者的差别。

针对replace和replaceAll命名的就说这么多,有时间把个人认为jdk中不好的一些define都拿出来记录一下,以免以后犯同样的错误。

原创粉丝点击