查找并替换字符串

时间:2011-04-26 01:43:51

标签: java

我正在尝试查找和替换字符串。以下是我所熟悉的内容。 我对如何强制所有更改显示在一行中感到困扰,如下所示。

Strings source = "parameter='1010',parameter="1011",parameter="1012" ";
Expected result = "parameter='1013',parameter="1015",parameter="1009" ";


Strings fin1 = "1010";

Strings fin2 = "1011";

Strings fin3 = "1012";

Strings rpl1 = "1013";

Strings rpl1 = "1015";

Strings rp21 = "1009";

Pattern pattern1 = Pattern.compile(fin1);
Pattern pattern2 = Pattern.compile(fin2);
Pattern pattern3 = Pattern.compile(fin3);

Matcher matcher1 = pattern1.matcher(source);  
Matcher matcher2 = pattern2.matcher(source); 
Matcher matcher3 = pattern3.matcher(source);

String output1  = matcher1 .replaceAll(rpl1);
String output2  = matcher2 .replaceAll(rpl2);
String output3  = matcher3 .replaceAll(rpl3);

感谢,

3 个答案:

答案 0 :(得分:2)

您可以使用replaceAll(..)上定义的String方法:

String source = "parameter='1010',parameter='1011',parameter='1012' ";
source = source.replaceAll("1010", "1013");
source = source.replaceAll("1011", "1015");
source = source.replaceAll("1012", "1009");

或更简洁:

source = source.replaceAll("1010", "1013").replaceAll("1011", "1015").replaceAll("1012", "1009");

请注意,replaceAll(..)的第一个参数也被视为正则表达式。

答案 1 :(得分:2)

为什么不执行以下操作:

String result=source.replaceAll(fin1,rpl1).replaceAll(fin12,rpl2).replaceAll(fin3,rpll);
  

调用此方法   form str.replaceAll(regex,repl)   产生与结果完全相同的结果   表达   Pattern.compile(正则表达式).matcher(STR).replaceAll(REPL)

所以你不必进行正则表达式等的所有中间编译。

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#replaceAll(java.lang.String,java.lang.String)

答案 2 :(得分:2)

这应该这样做:

public class Main {
    public static void main(String[] args) {
        String source = "parameter='1010',parameter='1011',parameter='1012' ";

        String fin1 = "1010";
        String fin2 = "1011";
        String fin3 = "1012";

        String rpl1 = "1013";
        String rpl2 = "1015";
        String rpl3 = "1009";

        source = source.replaceAll(fin1, rpl1).replaceAll(fin2, rpl2).replaceAll(fin3, rpl3);

        System.out.println("Result: " + source);
    }
}
相关问题