获取Java中带有正则表达式的单数或复数字符串

获取Java中带有正则表达式的单数或复数字符串,java,regex,replace,singular,plural,Java,Regex,Replace,Singular,Plural,我想将字符串中的变量替换为基于数字的单数/复数单词 我尝试过使用regex,但我不知道如何将regex和replaces结合使用 //输入:计数=2;variable=“带有2%SINGMULTI:number:numbers%的某些文本!” 公共静态字符串singmultiVAR(整数计数,字符串输入){ 如果(!input.contains(“SINGMULTI”)){ 返回null; } Matcher m=Pattern.compile(“\\%(.*?\\%”,Pattern.CASE

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

我尝试过使用regex,但我不知道如何将regex和replaces结合使用

//输入:计数=2;variable=“带有2%SINGMULTI:number:numbers%的某些文本!”
公共静态字符串singmultiVAR(整数计数,字符串输入){
如果(!input.contains(“SINGMULTI”)){
返回null;
}
Matcher m=Pattern.compile(“\\%(.*?\\%”,Pattern.CASE\u不区分大小写)。Matcher(输入);
如果(!m.find()){
抛出新的IllegalArgumentException(“无效输入!”);
}
字符串变量=m.group(1);
字符串[]varsplitted=varia.split(“:”);
返回计数==1?varsplitted[1]:varsplitted[2];
}
//输出:输入,但随后替换了SINGMULTI变量。

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

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

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

// 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");

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

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

// 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");

使用正则表达式替换循环

仅供参考:您还需要替换输入字符串中的数字,因此我使用
%COUNT%
作为标记

还要注意,
%
不是正则表达式中的特殊字符,因此无需转义它

此逻辑可以轻松扩展以支持更多替换标记

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

使用正则表达式替换循环

仅供参考:您还需要替换输入字符串中的数字,因此我使用
%COUNT%
作为标记

还要注意,
%
不是正则表达式中的特殊字符,因此无需转义它

此逻辑可以轻松扩展以支持更多替换标记

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

好的,但我准备好了,你仍然只得到了单数/复数的替换,而不是替换了变量的整个输入。还是我错了?@Stijnbanink你试过运行我的代码并检查吗?现在我有了。谢谢DOkay,但正如我所准备的,仍然只替换了单数/复数,而不是替换了该变量的整个输入。还是我错了?@Stijnbanink你试过运行我的代码并检查吗?现在我有了。谢谢D