开发者

find and replace strings

I am trying to find and replace strings. Below is what I have sofar. I am troubled on how to force all the changes to show in one line as showed below.

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


S开发者_StackOverflowtrings 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);

thanks,


You can use the replaceAll(..) method defined on String:

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

or more succinctly:

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

Note that the first parameter of replaceAll(..) is treated as a regular expression as well.


Why don't you do the following:

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

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

So you don't have to do all the intermediate compilation of regex etc.

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


This should do it:

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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜