Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

java - Insert Space After Capital letter

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.

P.S:I'm aware of using String.split and then combining.Just wanted to know if there is a better way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
String output = input.replaceAll("(\p{Ll})(\p{Lu})","$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).

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...