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}", "?");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With