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
withReplaceAll is rxr+foolishcat
所以这两个方法在命名上面给开发者的歧义性太大,不具备可读性,至少不能望文生义,replace替换成replaceWithLiteralTarget,replaceAll替换成replaceWithRegexTarget能够从语义上面区分出二者的差别。
针对replace和replaceAll命名的就说这么多,有时间把个人认为jdk中不好的一些define都拿出来记录一下,以免以后犯同样的错误。
- jdk中String对象的replace和replaceAll方法
- Java中的String的replace方法和replaceAll方法
- java String 类的replace 和replaceAll 方法替换“?”号
- String.Replace 和 String.ReplaceAll 的区别
- String,replace,replaceAll两方法的区别
- Java String replace() 和 replaceAll()的用法
- JAVA中string.replace()和string.replaceAll()的区别及用法 数据库中[]转义
- java中replace和replaceAll的区别
- java中replace和replaceAll的区别
- java中replace和replaceAll的区别
- java中replace和replaceAll的区别
- java中replace和replaceAll的区别
- java中replace和replaceAll的区别
- java中replace和replaceAll的区别
- java中replace和replaceAll的区别
- java中replace和replaceAll的区别
- JAVA中replace和replaceAll的区别
- JAVA中REPLACE和REPLACEALL的区别
- 架构如何才能抵制熵增
- Service Broker - Internal Dynamic Views
- 咖啡豆(JavaBean)·JSP中使用JavaBean
- socket通信 UDP文件传输(多客户端)——附源码
- 浅谈Android系统进程间通信(IPC)机制Binder中的Server和Client获得Service Manager接口之路
- jdk中String对象的replace和replaceAll方法
- java中关键字:static
- POJ-2559 维护单调栈.细节阿细节
- 差分约束——HDOJ 1529
- 完美解决:xcode4.2 修改__MyCompanyName__,终于让我找到方法了
- 敏捷开发一千零一问系列之十二:敏捷实施的步骤?
- Win7 RTM及win v pc RC体验
- 水题 hdu 1070 milk
- Serial ATA (SATA) chipsets — Linux support status