java replace会替换吗,java replace replaceAll 替换字符串的用法和区别实例

java replace replaceAll 是替换字符串最常用的方法,但实际上用法是有区别的,replace只能传字符不能传正则表达式,replaceAll 默认传入的就是正则表达式。下面是实例测试代码:

public class TestDemo {

public static void main(String[] args) {

//需求:实现在-x.txt替换成-9x.txt

String filename = “F:/kanbox/2014091-4.txt”;

String newname = filename.replaceAll(“-([0-9])”, “-9$1″);

System.out.println(newname);//F:/kanbox/2014091-94.txt

String newname2 = filename.replace(“-([0-9])”, “-9$1″);

System.out.println(newname2);//F:/kanbox/2014091-4.txt,没达到预期效果

String newname3 = filename.replace(“-”, “-9″);

System.out.println(newname3);//F:/kanbox/2014091-94.txt

}

}

扩展知识,api里面的说明:

String java.lang.String.replaceAll(String regex, String replacement)

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

An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression

————————————-

String java.lang.String.replace(CharSequence target, CharSequence replacement)

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”.

Parameters:

target The sequence of char values to be replaced

replacement The replacement sequence of char values

历史上的今天:

9bd101509341196819122f36086c9a60.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值