-4

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'?

krystal
  • 27
  • 6

3 Answers3

1

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"

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • 1
    This is really a quite difficult AI problem. For example, how would you want to parse the line "AloofPeople"? The method suggested would give "Alo of People" – FredK May 10 '18 at 18:40
  • Thank you very much! May I ask where did you learn to master this stuff? – krystal May 10 '18 at 18:42
  • @krystal Time and study... – Andreas May 10 '18 at 18:42
  • 1
    You made my day, @Andreas ! – Michael Piefel May 10 '18 at 18:44
  • and my day .... – revo May 10 '18 at 18:45
  • I was a bit surprised that negative look-ahead works for beginning of text. It would seem more logical to me to use `(?<!^)` negative look-behind. – Patrick Parker May 10 '18 at 19:08
  • @PatrickParker The match is zero-width, so even a look-ahead is still at beginning, so `^` matches. – Andreas May 10 '18 at 19:12
  • this means that we start looking for matches at a zero width position Before the beginning ^, which I find odd, and there is ambiguous support for matching at a zero width position between ^ and first char. I say ambiguous because negative look-behind works, but your version also works. – Patrick Parker May 10 '18 at 20:00
0

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.

-1

The easiest way is to use this:

"WordsofWisdom".replaceAll("(.....)(..)(......)", "$1 $2 $3") 
Michael Piefel
  • 18,660
  • 9
  • 81
  • 112
  • 1
    `"NotaGoodAnswer".replaceAll("(.....)(..)(......)", "$1 $2 $3")` gives `NotaG oo dAnswer` – Andreas May 10 '18 at 18:47
  • That doesn’t matter, since there are no prepositions in `NotaGoodAnswer` to begin with. Seriously though, your own answer gives `Nota Good Answer` which is not better. What’s the point of your comment here? From your own answer, I thought it was apparent you did not take the OP seriously. – Michael Piefel May 10 '18 at 19:04