Home: Perl Programming Help: Regular Expressions:
Regex split string into fixed length



hankcoder
New User

Sep 10, 2013, 12:10 AM


Views: 22038
Regex split string into fixed length

The below regex works great but result appear as "1-111-111" instead I want it to appear as "111-111-1".


Code
$line =~ s/(?<=\w)(?=(?:\w\w\w)+\b)/-/g;


I don't know how to change the regex above, tried several attempt but still not working.

Here is sample test code:


Code
my (@list) = ( "12", "123", "1234", "12345", "123456", "1234567", "234", "2345", "23456" ); 

foreach $line (@list)
{
$line =~ s/(?<=\w)(?=(?:\w\w\w)+\b)/-/g;
print "$line<br>";
}



BillKSmith
Veteran

Sep 10, 2013, 5:49 AM


Views: 22035
Re: [hankcoder] Regex split string into fixed length

The output of your sample code is nothing like your description. I have no idea what your real question is.
Good Luck,
Bill


hankcoder
New User

Sep 10, 2013, 6:16 AM


Views: 22030
Re: [BillKSmith] Regex split string into fixed length


In Reply To
The output of your sample code is nothing like your description. I have no idea what your real question is.



There is no error in sample program code only the result not appear as I wanted with given regex. I want it appear as


Code
123-4 
123-45
123-456
123-456-7

NOT

1-234
12-345
123-456
1-234-567


Need some help in minor modification to the regex.


BillKSmith
Veteran

Sep 10, 2013, 6:49 AM


Views: 22027
Re: [hankcoder] Regex split string into fixed length


Code
    $line =~ s/( \d{3} (?!$) )/$1-/xg;

Good Luck,
Bill


hankcoder
New User

Sep 10, 2013, 7:08 AM


Views: 22026
Re: [BillKSmith] Regex split string into fixed length

Wow, thank you Bill, you saved my day. I replaced \d with \w as $line may contain non-digits.


Code
$line =~ s/(\w{3}(?!$))/$1-/xg;



Laurent_R
Veteran / Moderator

Sep 10, 2013, 8:25 AM


Views: 22021
Re: [hankcoder] Regex split string into fixed length

You've received many answers on your cross post on Perlmonks.