Reputation: 1067
I have a string like this "HelloWorldMyNameIsCarl" and I want it to become something like "Hello_World_My_Name_Is_Carl". How can I do this?
Upvotes: 6
Views: 12662
Reputation: 9440
Yes, regular expressions can do that for you:
"HelloWorldMyNameIsCarl".replaceAll("(.)([A-Z])", "$1_$2")
The expression [A-Z]
will match every upper case letter and put it into the second group. You need the first group .
to avoid replacing the first 'H'.
As Piligrim pointed out, this solution does not work for arbitrary languages. To catch any uppercase letter defined by the Unicode stardard we need the Unicode 4.1 subproperty \p{Lu}
which matches all uppercase letters. So the more general solution looks like
"HelloWorldMyNameIsCarl".replaceAll("(.)(\\p{Lu})", "$1_$2")
Thanks Piligrim.
Upvotes: 37
Reputation: 100706
Is this homework? To get you started:
java.lang.Character
class will help)Upvotes: 3
Reputation: 48369
Here's a hint to get you thinking along a possible solution:
Useful keywords:
Upvotes: 2