How can I add an underscore before each capital letter inside a Java String? -
I have a string like "HelloWorldMyNameIsCarl" and I want to create something like "Hello_World_My_Name_Is_Carl". How can I do this?
Yes, regular expressions can do this for you:
< [AZ ]
"HelloWorldMyNameIsCarl" .replaceAll ("(. ((.) ([AZ])", "$ 1_ $ 2")
expression [AZ]
will match each upper case sheet and it will be inserted into another group. To avoid changing the first 'H' you have to first group .
is required.
As mentioned, this solution does not work for arbitrary language. To capture any uppercase letters defined by Unicode Stargard, we need the \ p {Lu}
which matches all the uppercase letters, therefore the more general solution
"HelloWorldMyNameIsCarl" .replaceAll ("(.) (\\ p {Lu})", "$ 1_ $ 2") appears
Thanksgiving
Comments
Post a Comment