So I have a string like
Refurbished Engine for 2000cc Vehicles
I would like to turn this into
Refurbish
You could perhaps do:
String text = text.replaceAll("(?<=\\b[0-9]{4})cc\\b", "CC");
(?<=\\b[0-9]{4})
is a positive lookbehind that will ensure a match only if cc
is preceded by 4 digits (no more than 4 and this rule is enforced by the word boundary \\b
(this matches only at the ends of a word, where a word is defined as a group of characters matching \\w+
). Also, since lookbehinds are zero-width assertions, they don't count in the match.
If the number of cc's can vary, then it might be easiest checking only one number:
String text = text.replaceAll("(?<=[0-9])cc\\b", "CC");