Java Regex To Uppercase

So I have a string like

Reconditioned engine for 2000 cc vehicles feet

I would like to turn this into

Remanufactured engine for 2000CC vehicles

With capital cc at 2000CC. I obviously can't do text.replaceAll("cc","CC");it because it would replace all occurrences with cc versions of capital so that the word accelerator becomes aCCelerator. In my case, the leading four digits will always be four digits followed by the letters cc, so I suppose this can be done with a regex.

My question is, how in Java can I translate cc to CC when it is 4 digits and get the result that I expect above?

String text = text.replaceAll("[0-9]{4}[c]{2}", "?");
+4
source share
4 answers

cc , , cc.

Java one-liner. Matcher#appendReplacement() Matcher#appendTail():

String str = "Refurbished Engine for 2000cc Vehicles";
Pattern pattern = Pattern.compile("\\d{4}cc");
Matcher matcher = pattern.matcher(str);

StringBuffer result = new StringBuffer();
while (matcher.find()) {
    matcher.appendReplacement(result, matcher.group().toUpperCase());
}

matcher.appendTail(result);

System.out.println(result.toString());
+3

text = text.replaceAll("(\\d{4})cc", "$1CC");
//                          ↓          ↑
//                          +→→→→→→→→→→+

, ( ), ( $x, x - ).

"\\b", , - , look-adound , - / .

+7

- (), :

:

public static void main(String [] args) {
    String s = "1000cc abc 9999cc";
    String t = s.replaceAll("(\\d{4})cc", "$1CC");
    System.err.println(t);
}
+2

:

String text = text.replaceAll("(?<=\\b[0-9]{4})cc\\b", "CC");

(?<=\\b[0-9]{4})- this is a positive lookbehind, which will ensure compliance only if ccfour digits precede (no more than 4, and this rule is applied by the word boundary \\b(this corresponds only to the ends of the word, where the word is defined as a group of characters matching \\w+) .In addition, since lookbehinds are zero-width statements; they are not taken into account in a match.

If the amount of cc can change, then it would be easiest to check only one number:

String text = text.replaceAll("(?<=[0-9])cc\\b", "CC");
+2
source

Source: https://habr.com/ru/post/1526395/


All Articles