我有字母'WordsofWisdom' 如果我申请这个:
replaceAll("([^_])([A-Z])", "$1 $2")
它会产生'智慧之言',但是我必须写什么才能在'of'之前获得一个空格?
答案 0 :(得分:1)
使用零宽度正向前瞻(?=xxx)
,结合备选方案列表|
,并匹配所有Unicode大写字母\p{Lu}
,然后将零宽度匹配替换为单个空间:
"WordsoftheWise".replaceAll("(?=\\p{Lu}|of|the)", " ")
结果:" Words of the Wise"
如果您不想在第一个字母之前添加空格,请添加零宽度否定前瞻(?!xxx)
,以防止匹配文本的开头^
:
"WordsoftheWise".replaceAll("(?!^)(?=\\p{Lu}|of|the)", " ")
结果:"Words of the Wise"
答案 1 :(得分:0)
为了实现这一点,您需要以某种方式首先识别字符串中间的单词。 indexOf方法将识别""的起始索引。在字符串中。然后,您可以将这三个单词连接在一起。
答案 2 :(得分:-1)
最简单的方法是使用它:
"WordsofWisdom".replaceAll("(.....)(..)(......)", "$1 $2 $3")