CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



hankcoder
New User

Sep 10, 2013, 12:10 AM

Post #1 of 6 (10641 views)
Regex split string into fixed length Can't Post

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

Post #2 of 6 (10638 views)
Re: [hankcoder] Regex split string into fixed length [In reply to] Can't Post

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

Post #3 of 6 (10633 views)
Re: [BillKSmith] Regex split string into fixed length [In reply to] Can't Post


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

Post #4 of 6 (10630 views)
Re: [hankcoder] Regex split string into fixed length [In reply to] Can't Post


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

Good Luck,
Bill


hankcoder
New User

Sep 10, 2013, 7:08 AM

Post #5 of 6 (10629 views)
Re: [BillKSmith] Regex split string into fixed length [In reply to] Can't Post

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

Post #6 of 6 (10624 views)
Re: [hankcoder] Regex split string into fixed length [In reply to] Can't Post

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

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives