0

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?

stijnb1234
  • 184
  • 4
  • 19

2 Answers2

1

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");
Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

Use a regex replacement loop.

FYI: You also need to replace the number in the input string, so I'm using %COUNT% as the marker for that.

Also note that % is not a special character in a regex, so no need to escape it.

This logic can easily be expanded to support more replacement markers.

public static String singmultiVAR(int count, String input) {
    StringBuilder buf = new StringBuilder(); // Use StringBuffer in Java <= 8
    Matcher m = Pattern.compile("%(?:(COUNT)|SINGMULTI:([^:%]+):([^:%]+))%").matcher(input);
    while (m.find()) {
        if (m.start(1) != -1) { // found %COUNT%
            m.appendReplacement(buf, Integer.toString(count));
        } else { // found %SINGMULTI:x:y%
            m.appendReplacement(buf, (count == 1 ? m.group(2) : m.group(3)));
        }
    }
    return m.appendTail(buf).toString();
}

Test

for (int count = 0; count < 4; count++)
    System.out.println(singmultiVAR(count, "Some text with %COUNT% %SINGMULTI:number:numbers%!"));

Output

Some text with 0 numbers!
Some text with 1 number!
Some text with 2 numbers!
Some text with 3 numbers!
Andreas
  • 154,647
  • 11
  • 152
  • 247