VERY easy question:

$string="1234123412341234"
I want $string2="1234 1234 1234 1234" from string1 value.
Most efficient/shortly/etc.. way to do that??
steph84Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
ozoConnect With a Mentor Commented:
$string2=join' ',$string=~/(.{1,4})/g;
#don't need the /s if you have only digits,
#{1,4} in case there's not enough digits to fill the last group of 4
0
 
ozoCommented:
$string=~s/41/4 1/g;
0
 
ozoCommented:
#it's not obvious what you might want if
#$string='a ab abcd  abcde abcdef abcdefg abcdefgh abcdefghi'
#some possibilities include:
($string2=$string)=~s/(\S{4})\B/$1 /g;
#or
$string2=join' ',($string=~/(....)/gs;
0
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

 
steph84Author Commented:
In fact, it was obvious...for me!
I just wanted to make group of 4 chars or digits, separated by one blank space.
The last answer is exactly what I was looking for.
you should answer now so I could grade you!!

0
 
steph84Author Commented:
In fact, it was obvious...for me!
I just wanted to make group of 4 chars or digits, separated by one blank space.
The last answer is exactly what I was looking for.
you should answer now so I could grade you!!

0
 
hedjCommented:
$string="1234123412341234"
$string =~ s/4/4 /g;
0
 
ozoCommented:
That puts a space at the end of $string which may not have been wanted.

What if $string contains non-digits, or groups of less than 4 digits separated by spaces?
Should those spaces be removed before regrouping them in fours?
0
 
steph84Author Commented:
Sorry hedj, but points are for ozo....
Ozo, no worrying about $string, they'll never have sapce or non digit char.
Thanks for all possibilities, that's what I'm looking for when I ask a question (especially as easy as this one) on experts-exchange..
You should answer!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.