Search code examples
javaregexparseint

Replacing Strings with a number in it without a for loop


So I currently have this code;

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

Which works well, but I would like to just keep it simple (using Pattern matching) so I used this code to check if it matches;

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

StringUtil's matches;

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();
}

Which returns true, then comes the next part I need help with, replacing the {place5} so I can parse the number. I could replace "{place" and "}", but what if there were multiple of those in a string ("{place5} {username}"), then I can't do that anymore, as far as I'm aware, if you know if there is a simple way to do that then please let me know, if not I can just stick with the for-loop.


Solution

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

    In order to obtain the number after {place, you can use

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

    The regex matches arbitrary number of characters before the string we are searching for, then {place, then we match and capture 1 or more digits with (\d+), and then we match the rest of the string with .*. Note that if the string has newline symbols, you should append (?s) at the beginning of the pattern. $1 in the replacement pattern "restores" the value we need.