[英]Get singular or Plural string with regex in Java
我想將字符串中的變量替換為基於數字的單數/復數詞。
我嘗試使用正則表達式,但我不知道如何使用正則表達式和替換的組合。
//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.
它現在只輸出變量,而不是整個輸入。 我需要如何將其添加到代碼中?
您可以使用Matche
的replaceAll
方法來替換匹配的字符串。
其實,你不必分割字符串,你可以匹配的:
在你的正則表達式:
// 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();
}
測試
for (int count = 0; count < 4; count++)
System.out.println(singmultiVAR(count, "Some text with %COUNT% %SINGMULTI:number:numbers%!"));
輸出
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.