我想将字符串中的variabel替换为基于数字的单/复数单词。

我试图使用正则表达式,但是我不知道如何使用正则表达式和替换的组合。

//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.


现在,它仅输出变量,而不输出整个输入。我该如何将其添加到代码中?

最佳答案

您可以使用MatchereplaceAll方法替换匹配的字符串。

实际上,您不必拆分字符串,只需在正则表达式中匹配:即可:

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


如果计数为1,请替换为组1,否则请替换为组2:

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

10-06 05:47
查看更多