So I have a string like
Refurbished Engine for 2000cc Vehicles
I would like to turn this into
Refurbish
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.