DulcimerDude DulcimerDude - 2 years ago 91
Perl Question

Perl - How do I insert a space between an alpha character and a numeric character?

This is a continuation of my original question:
Perl- How do I insert a space before each capital letter except for the first occurance or existing?

I was able to achieve a desired result of inserting spaces between caps with only letters in the string:

my $camel ="SomeCamel IsEnteringText";
$camel =~ s/(?<=[a-z])(?=[A-Z])/ /g;
$camel =~ s/([^[:space:]]+)/\u$1/g;

Prints "Some Camel Is Entering Text"
Thanks for the help.

But, when numbers are present, I ran into issues.

my $camel ="Some 440Camel220 IsEntering100Text Nogo";
$camel =~ s/(?<=[a-z])(?=[A-Z])/ /g;
$camel =~ s/([^[:space:]]+)/\u$1/g;

Prints "Some 440Camel220 Is Entering100Text Nogo"

Desired "Some 440 Camel 220 Is Entering 100 Text Nogo"

I keep trying and failing. Camels are seemingly pretty tough especially with a couple numbers in 'em...

So, How do I now insert a space between the letters and the numbers?

Thanks in advance for another learning experience here....

Answer Source

Change the first substitution to be:

$camel =~ s/(?<=[a-z])(?=[A-Z0-9])|(?<=[0-9])(?=[A-Z])/ /g;

See also perldoc perlre.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download