大写字母后插入空格 [英] Insert Space After Capital letter
问题描述
如何将HelloWorld
转换为Hello World
。拆分必须基于The大写字母,但应排除第一个字母。
How to covert "HelloWorld"
to "Hello World"
.The splitting has to take place based on The Upper-Case letters ,but should exclude the first letter.
PS :我知道使用String.split然后合并。只是想知道是否有更好的方法。
P.S:I'm aware of using String.split and then combining.Just wanted to know if there is a better way.
推荐答案
String output = input.replaceAll("(\\p{Ll})(\\p{Lu})","$1 $2");
此正则表达式搜索一个小写字母,后面跟一个大写字母,并将它们替换为前者,一个空格和后者(有效地将它们与空间隔开)。它将每个都放在一个捕获组()
中,以便能够通过反向引用重用替换字符串中的值( $ 1
和 $ 2
)。
This regex searches for a lowercase letter follwed by an uppercase letter and replaces them with the former, a space and the latter (effectively separating them with a space). It puts each of them in a capturing group ()
in order to be able to re-use the values in the replacement string via back references ($1
and $2
).
要查找大写和小写字母,请使用 \p {Ll}
和 \p {Lu}
(而不是 [az]
和 [AZ]
),因为它处理Unicode标准中的所有大写和小写字母,而不仅仅是那些在ASCII范围内(在正则表达式中对Unicode的这个很好的解释主要适用于Java) 。
To find upper- and lowercase letters it uses \p{Ll}
and \p{Lu}
(instead of [a-z]
and [A-Z]
), because it handles all upper- and lowercase letters in the Unicode standard and not just the ones in the ASCII range (this nice explanation of Unicode in regexes mostly applies to Java as well).
这篇关于大写字母后插入空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!