在没有for循环的情况下用其中的数字替换字符串

Replacing Strings with a number in it without a for loop

所以我目前有这个代码;

for (int i = 1; i <= this.max; i++) {
    in = in.replace("{place" + i + "}", this.getUser(i)); // Get the place of a user.
}

效果很好,但我想保持简单(使用模式匹配) 所以我用这段代码来检查它是否匹配;

System.out.println(StringUtil.matches("{place5}", "\{place\d\}"));

StringUtil 的匹配;

public static boolean matches(String string, String regex) {
    if (string == null || regex == null) return false;
    Pattern compiledPattern = Pattern.compile(regex);
    return compiledPattern.matcher(string).matches();
}

returns 正确,然后是我需要帮助的下一部分,替换 {place5} 以便我可以解析数字。我可以替换“{place”和“}”,但如果字符串中有多个(“{place5} {username}”)怎么办,据我所知,我不能再这样做了,如果您知道是否有一种简单的方法可以做到这一点,请告诉我,如果没有,我可以坚持使用 for 循环。

then comes the next part I need help with, replacing the {place5} so I can parse the number

为了得到{place之后的数字,可以使用

s = s.replaceAll(".*\{place(\d+)}.*", "");

正则表达式匹配我们正在搜索的字符串之前的任意数量的字符,然后是{place,然后我们用[=13匹配并捕获 1个或多个数字=],然后我们将字符串的其余部分与 .* 匹配。请注意,如果字符串有换行符,则应在模式开头附加 (?s) 在替换模式中 "restores" 我们需要的值。