使用JAVA将单个字符串中的2个部分替换为其他字符串

时间:2017-03-29 04:04:09

标签: java

我有一个字符串:

{abc} say hello to {def};

You say hello to {abc};

现在我想这样替换这句话:

Peter say hello to Sally;

You say hello to Peter

其中{abc}和{def}是用户的ID,因此我需要在{}中获取字符串。然后替换这些词。我怎样才能得到{}

中的文字

我尝试使用.indexOf和.substring来使其工作。但我认为这不是一个好主意,因为它需要很多代码才能处理两种。 我的方法:

String sentence = {abc} say hello to {def};
int firstOpen = sentence.indexOf("{");
int firstClose = sentence.indexOf("}");
int secondOpen = sentence.lastIndexOf("{");
int secondClose = sentence.lastIndexOf("}");
String firstName = sentence.subSting(firstOpen + 1, firstClose);
String secondName = sentence.subSting(secondOpen + 1, secondClose);
...
sentence = "Peter" + sentence.substring(firstClose, secondOpen) .....

3 个答案:

答案 0 :(得分:1)

只需使用String.replace

即可
insertionsort U = insertionsort() ;
collectionObj.sort(U, greater) ;

答案 1 :(得分:0)

如果您不确定花括号内的单词是什么,那么您可以使用这些正则表达式使它们成为通用的

input = input.replaceFirst("^\\{([^}]*)\\}", "Peter").replaceFirst("\\{([^}]*)\\};$", "Sally");

输出:

Peter say hello to Sally

如果要保存组ID,可以使用此程序。

<强>输出

first Id: abc                                                                                                                                                                                              
second Id: def                                                                                                                                                                                             
replaced String: Peter say hello to Sally

代码#2

import java.util.regex.*;

public class HelloWorld {

    public static void main(String[] args) {
        String line = "{abc} say hello to {def};";

        Matcher m = Pattern.compile("^\\{([^}]*)\\}(.*)\\{([^}]*)\\};$").matcher(line);
        if (m.find()) {
            System.out.println("first Id: " + m.group(1));
            System.out.println("second Id: " + m.group(3));
            System.out.println("replaced String: " + "Peter" + m.group(2) + "Sally");
        }
    }
}

答案 2 :(得分:-1)

您可以使用String.replaceFirst方法

String sentence = "{abc} say hello to {def}";
String firstChange = sentence.replaceFirst("\\{abc\\}","you");
String secondChange = firstChagne.replaceFirst("\\{def\\}","Peter");