在所有事件中替换某些词之间的所有字符

时间:2017-12-22 16:43:29

标签: java replace replaceall

替换" b"之间的所有字符。和" g"在JAVA

我有一个字符串(输入

String s="abcdefghabcdefghij";

我需要输出(输出

ab*ghab**ghij

4 个答案:

答案 0 :(得分:2)

这应该有效:

String st = s.replace("cdef", "*");

然后使用新字符串

或者您可以使用新值保留旧变量

s = s.replace("cdef", "*");

答案 1 :(得分:1)

如果你想要替换b和g之间的所有东西,你可以使用:

String s = "abcdefghabcdefghij";
s = s.replaceAll("(.*b)(.*?)(g.*)", "$1*$2");//output = ab*ghab*cdef

但是输出与您的输出不匹配,相反,您可以使用Pattern来解决您的问题:

String s = "abcdefghabcdefghij";
Pattern pattern = Pattern.compile("b(.*?)g");
Matcher matcher = pattern.matcher(s);
int i = 1;
while (matcher.find()) {
    String group = matcher.group(1);//match every thing between b and g
    //create n (*) based on the number of Iteration, the 1st only one star the second 2 ..
    //and use replaceFirst to replace the first matches
    s = s.replaceFirst(group, String.format("%0" + i++ + "d", 0).replace("0", "*"));
}
System.out.println(s);// output ab*ghab**ghij

答案 2 :(得分:0)

Pattern p = Pattern.compile("b(.*?)g");
String[] arr = { "abcdefghabcdefghij" };
for (String str : arr) {
    String s = p.matcher(str).replaceAll("b*g");
    System.out.printf("%s, %s\n", str, s);
}

我假设**是拼写错误,如果不是,那么使用一些计数器来放置所需数量的*。

答案 3 :(得分:0)

和@sanit一样,我假设**是一个拼写错误,并且星号计数不会根据替换次数递增:

  • 选项1:" bg"被硬编码到替换字符串中

    String string = "abcdefghabcdefghij";
    string = string.replaceAll("b.*?g", "b*g");
    System.out.println(string);
    
  • 选项2:更灵活一点。 " BG"不是硬编码的:

    String string = "abcdefghabcdefghij";
    while (string.matches("b.*?g")) {
        String curMatch = string.substring(string.indexOf("b") + 1, string.indexOf("g"));                                               
        string = string.replaceFirst(curMatch, "*");
    }