有没有办法在java中的两个给定模式之间用@替换所有char

时间:2015-09-07 07:28:49

标签: java

我有一个像这样的字符串

Hello #'World'# , currently i am in #'world's'# best location.

我需要在java中使用regex替换#''#之间的所有字符 我需要一个最终的字符串应该是这种格式

Hello #'@@@@@'# , currently i am in #'@@@@@@@'# best location.

1 个答案:

答案 0 :(得分:1)

解决方案不使用正则表达式:

String input = "Hello #'World'# , currently i am in #'world's'# best location.";

StringBuilder buf = new StringBuilder(input.length());
int start = 0, idx1, idx2;
while ((idx1 = input.indexOf("#'", start)) != -1) {
    idx1 += 2;
    if ((idx2 = input.indexOf("'#", idx1)) == -1)
        break;
    buf.append(input, start, idx1); // append text up to and incl. "#'"
    for (; idx1 < idx2; idx1++)
        buf.append('@'); // append replacement characters
    start = idx2 + 2;
    buf.append(input, idx2, start); // append "'#"
}
buf.append(input, start, input.length()); // append text after last "'#"
String output = buf.toString();

System.out.println(input);
System.out.println(output);

输出

Hello #'World'# , currently i am in #'world's'# best location.
Hello #'@@@@@'# , currently i am in #'@@@@@@@'# best location.