I have a string like:
SomeCamel WasEnteringText
I have found various means of splitting up the string and inserting spaces with php str_replace but, i need it in perl.
Sometimes there may be a space before the string, sometimes not. Sometimes there will be a space in the string but, sometimes not.
I tried:
my $camel = "SomeCamel WasEnteringText";
#or
my $camel = " SomeCamel WasEntering Text";
$camel =~ s/^[A-Z]/\s[A-Z]/g;
#and
$camel =~ s/([\w']+)/\u$1/g;
and many more combinations of =~s//g; after much reading.
I need a guru to direct this camel towards an oasis of answers.
OK, based on the input below I now have:
$camel =~ s/([A-Z])/ $1/g;
$camel =~ s/^ //; # Strip out starting whitespace
$camel =~ s/([^[:space:]]+)/\u$1/g;
Which gets it done but seems excessive. Works though.
Try:
Please note that the obvious try of
$camel =~ s/([^ ])([A-Z])/$1 $2/g;
has a bug: it doesn't work if there are capital letters following one another (e.g. "ABCD" will be transformed into "ABCD" and not "A B C D")Try : s/(?<=[a-z])(?=[A-Z])/ /g
This inserts as space after a lower case character (ie not a space or start of string) and before and upper case character.
And the less "screw this horsecrap" version:
EDIT: I noticed that this also adds extra whitespace when you add punctuation into the mix, which probably isn't what the OP wants; thankfully, the fix is simply changing the negative look ahead from \s+ to \W+. Although now I'm beginning to wonder why I actually added those pluses. Drats, me!
EDIT2: Erm, apologies, originally forgot the /g flag.
EDIT3: Okay, someone downvote me. I went retarded. No need for the negative lookbehind for ^ - I really dropped the ball on this one. Hopefully fixed:
1: http://perldoc.perl.org/perlre.html
Improving ...
... on Hughmeir's, this works also with numbers and words starting with lower-case letters.
Tests