Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex To Uppercase

Tags:

java

regex

So I have a string like

Refurbished Engine for 2000cc Vehicles

I would like to turn this into

Refurbished Engine for 2000CC Vehicles

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

My question is how in Java can I turn the cc into CC when it follows 4 digits and obtain the result I am expecting above?

String text = text.replaceAll("[0-9]{4}[c]{2}", "?");
like image 637
Ashley Swatton Avatar asked Dec 06 '22 03:12

Ashley Swatton


1 Answers

You can try with

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

Trick is to place number in group (via parenthesis) and later use match from this group in replacement part (via $x where x is group number).

You can surround that regex with word boundaries "\\b" if you want to make sure that matched text is not part of some other word. You can also use look-adound mechanisms to ensure that there are no alphanumeric characters before and/or after matched text.

like image 111
Pshemo Avatar answered Dec 16 '22 15:12

Pshemo