我正在用java编程,我需要替换String中的某些关键字。
假设我的字符串是"Int hello1 \n Int hello11",我想将"hello1"替换为"a","hello11"替换为"b"。
问题是当我说String.replaceAll("hello1", "a");原始字符串保持如下:Int a \n Int a1,如何防止替换hello11?
我该用什么药?
发布于 2014-08-11 10:23:54
你可以用单词边界来处理这个问题。
您还需要将由String调用创建的replaceAll分配给另一个变量,因为String是不可变的。
在本例中,我只是通过标准输出流打印它。
String input = "Int hello1 \n Int hello11";
System.out.println(input.replaceAll("\\bhello1\\b", "a"));输出
Int a
Int hello11发布于 2014-08-11 10:23:54
您需要在正则表达式中使用word边界:
String repl = str.replaceAll("\\bhello1\\b", "a");
repl = str.replaceAll("\\bhello11\\b", "b");发布于 2014-08-11 10:21:14
Java字符串对象是不可变的,因此您不能更改它们。
将返回的值从replaceAll()方法重新分配到该变量。
String str = "Int hello1 \n Int hello11";
String yourStr = str.replaceAll("\\bhello1\\", "a");您甚至可以像下面这样重新分配返回的值。
str = str.replaceAll("\\bhello1\\", "a");https://stackoverflow.com/questions/25240988
复制相似问题