简体   繁体   English

在 Java 中使用正则表达式获取单数或复数字符串

[英]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?我需要如何将其添加到代码中?

You can use Matche 's replaceAll method to replace the matched string.您可以使用MatchereplaceAll方法来替换匹配的字符串。

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:如果计数为 1,则替换为组 1,否则替换为组 2:

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

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.仅供参考:您还需要替换输入字符串中的数字,因此我使用%COUNT%作为标记。

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!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM