javaregexreplacesingularplural

Get singular or Plural string with regex in Java


I want to replace a variabel in a String to a singular/plural word based on a number.

I've tried to use regex, but I don't know how to use a combination of regex and replaces.

//INPUTS: count = 2; variable = "Some text with 2 %SINGMULTI:number:numbers%!"
public static String singmultiVAR(int count, String input) {
    if (!input.contains("SINGMULTI")) {
        return null;
    }

    Matcher m = Pattern.compile("\\%(.*?)\\%", Pattern.CASE_INSENSITIVE).matcher(input);
    if (!m.find()) {
        throw new IllegalArgumentException("Invalid input!");
    }

    String varia = m.group(1);

    String[] varsplitted = varia.split(":");

    return count == 1 ? varsplitted[1] : varsplitted[2];
}
//OUTPUTS: The input but then with the SINGMULTI variable replaced.

It now only outputs the variable, but not the whole input. How do I need to add that to the code?


Solution

  • You can use Matche's replaceAll method to replace the matched string.

    In fact, you don't have to split the string, you can just match for the : in your regex:

    // You don't need the "if (!input.contains("SINGMULTI"))" check either!
    Matcher m = Pattern.compile("\\%SINGMULTI:(.*?):(.*?)\\%").matcher(input);
    

    If the count is 1, replace with group 1, otherwise replace with group 2:

    // after checking m.find()
    return m.replaceAll(count == 1 ? "$1" : "$2");