Java Regex To Uppercase

后端 未结 4 890
萌比男神i
萌比男神i 2021-01-19 10:27

So I have a string like

Refurbished Engine for 2000cc Vehicles

I would like to turn this into

Refurbish

4条回答
  •  孤街浪徒
    2021-01-19 11:16

    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");
    

提交回复
热议问题