I have the string 'WordsofWisdom' and if I apply this:
replaceAll("([^_])([A-Z])", "$1 $2")
it produces 'Wordsof Wisdom', but what do I have to write to obtain a space before the word 'of'?
I have the string 'WordsofWisdom' and if I apply this:
replaceAll("([^_])([A-Z])", "$1 $2")
it produces 'Wordsof Wisdom', but what do I have to write to obtain a space before the word 'of'?
Use a zero-width positive look-ahead (?=xxx)
, combined with list of alternatives |
, and matching of all Unicode uppercase letters \p{Lu}
, then replace the zero-width match with a single space:
"WordsoftheWise".replaceAll("(?=\\p{Lu}|of|the)", " ")
Result: " Words of the Wise"
If you don't want space added before first letter, add zero-width negative look-ahead (?!xxx)
, to prevent matching beginning of text ^
:
"WordsoftheWise".replaceAll("(?!^)(?=\\p{Lu}|of|the)", " ")
Result: "Words of the Wise"
In order to accomplish that, you would need to somehow first identify the word of in the middle of the string. The indexOf method will identify the starting index of "of" in the string. You can then concatenate the three words together.
The easiest way is to use this:
"WordsofWisdom".replaceAll("(.....)(..)(......)", "$1 $2 $3")