Hoa Vu
Hoa Vu

Reputation: 2933

Regex to split String with uppercase and lowercharacter

I am trying to split like: TwitterHashtagIsVeryCOMPLICATED

The string after being splited like: Twitter Hashtag Is Very COMPLICATED

Could I use regex to do that?

Thanks so much for any advices.

Upvotes: 2

Views: 1952

Answers (2)

Mena
Mena

Reputation: 48434

Edit strongly inspired by dasblinkenlight's answer (+1 for that). I only change to Unicode categories here for Unicode support:

String test = "TwitterHashtagIsVeryCOMPLICATED";
for (String splitted: test.split("(?<=\\p{Ll})(?=\\p{Lu})")) {
    System.out.println(splitted);
}

Output:

Twitter
Hashtag
Is
Very
COMPLICATED

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

This should work:

str.split("(?<=[a-z])(?=[A-Z])")

The idea is to use zero-length lookbehind for a lowercase letter, and zero-length lookahead for the uppercase letter. This construct would match only at the "word breaks" in camel case strings.

Here is a demo on ideone.

Upvotes: 5

Related Questions