替换所有出现的子字符串,一次一个

时间:2017-11-17 17:34:53

标签: java string

我有以下方法用{TIMESTAMP}返回的值替换所有出现的String.valueOf(System.nanoTime())子字符串,目的是为每个子字符串出现一个不同的时间标记,但它会导致所有子字符串由相同的值替换。

class StringUtils {
    private static String resolveTimestamp(String s) {
        String timestamp = "\\{TIMESTAMP}";
        return s.replaceAll(timestamp, String.valueOf(System.currentTimeMillis()));
    }
}

class Sample {
    public static void main(String[] args) {
        StringUtils.resolveTimestamp("{TIMESTAMP}, {TIMESTAMP}, {TIMESTAMP}")
    }
}

// The execution of the code above would result in:
// 241170886964203, 241170886964203, 241170886964203

// But I want to get this:
// 241733154573329, 241734822930540, 241751957270934

我想知道哪种方法可以做我想做的事情,因为现在有几种方法可以解决这个问题:

  • s.matches(timestamp)为条件循环遍历每个子字符串的循环,s.replaceFirst(timestamp, String.valueOf(System.nanoTime()))在循环内执行替换。
  • 使用子字符串将字符串分解为多个s.split(timestamp)的块,并使用String.valueOf(System.nanoTime()))
  • 返回的值迭代连接每个字符串的块
  • 可能还有其他一些选择

注意:请注意,这与in this question解决的问题不同。在那里,他们需要用相同的值替换几次出现的固定模式,而我需要替换相同子串的多次出现,每次出现在运行时计算的不同值。

3 个答案:

答案 0 :(得分:2)

您想要做的就是修改:replaceAll replaceFirst 这样每次你用字符串调用方法时 - 它只会替换下一个出现的地方:

public static void main(String[] args) {
    String req = "\\{TIMESTAMP} \\{TIMESTAMP} \\{TIMESTAMP} \\{TIMESTAMP}";
    req = resolveTimestamp(req);
    req = resolveTimestamp(req);
    req = resolveTimestamp(req);
    req = resolveTimestamp(req);
    System.out.println("req = " + req);
}

private static String resolveTimestamp(String s) {
    String timestamp = "\\{TIMESTAMP}";
    return s.replaceFirst(timestamp, String.valueOf(System.currentTimeMillis()));
}

<强>输出:

req = \1510940324918 \1510940324921 \1510940324921 \1510940324921

评论:如果您想要更高的精确度,则应考虑使用System.nanoTime()代替System.currentTimeMillis()

答案 1 :(得分:2)

您可以使用String.replaceFirst:

private static String resolveTimestamp(String s) {
    String timestamp = "\\{TIMESTAMP}";

    while(s.matches(timestamp)) {
       s = s.replaceFirst(timestamp, String.valueOf(System.nanoTime()));
    }
    return s;
}

答案 2 :(得分:0)

您需要调用一个方法在replace all方法中返回一个随机字符串。

str.replaceAll("timestamp", randomTimestamp());

private String randomTimestamp() {
    Random rand = new Random(); 
    int randomNumber= rand.nextInt(1000);
    return String.valueOf(System.currentTimeMillis() + randomNumber);
}