Home: Perl Programming Help: Regular Expressions:
How to change [1,2,3] to [1][2][3]



tacallah
New User

Feb 11, 2009, 6:31 AM


Views: 10175
How to change [1,2,3] to [1][2][3]

I am trying to write a regular expression to do the following:

[#,#,#] => [#][#][#]
[ # , # , # ] => [#][#][#]

Here is what I have tried:

my $x = "[3,4,5]\n[ 3 , 4 , 5 ]\n";
print "BEFORE\n$x";
$x =~ s/(?<=\[)\s*(\d+)\s*,/$1][/g;
print "AFTER\n$x";

>>> OUTPUT <<<
BEFORE
[3,4,5]
[ 3 , 4 , 5 ]
AFTER
[3][4,5]
[3][ 4 , 5 ]

The following will work by using a while loop:

my $x = "[3,4,5]\n[ 3 , 4 , 5 ]\n";
print "BEFORE\n$x";
while ($x =~ s/\[\s*(\d+)\s*,/[$1][/g) {}
$x =~ s/\[\s*(\d+)\s*\]/[$1]/g;
print "AFTER\n$x";

>>> OUTPUT <<<
BEFORE
[3,4,5]
[ 3 , 4 , 5 ]
AFTER
[3][4][5]
[3][4][5]

Is there any way to this with a single substitute?

Thanks!


KevinR
Veteran


Feb 11, 2009, 4:06 PM


Views: 10165
Re: [tacallah] How to change [1,2,3] to [1][2][3]


Code
my $x = "[3,4,5]\n[ 3 , 4 , 5 ]\n"; 
$x =~ s/([\[,]?)\s*(\d+)\s*([,\]]?)/[$2]/g;
print $x;

-------------------------------------------------


tacallah
New User

Feb 11, 2009, 9:00 PM


Views: 10158
Re: [KevinR] How to change [1,2,3] to [1][2][3]

Thanks for your reply. Your solution does work for the string which I gave, but it could produce wrong results:

[1] 2 [3] => [1][2][3]
1, 2, 3 => [1][2][3]
<1> has 1 inside. => <[1]> has[1]inside.

I appreciate your effort. I am hoping to find a regular expression that only changes numbers enclosed within square brackets.


KevinR
Veteran


Feb 11, 2009, 10:28 PM


Views: 10152
Re: [tacallah] How to change [1,2,3] to [1][2][3]


In Reply To
Thanks for your reply. Your solution does work for the string which I gave, but it could produce wrong results:

[1] 2 [3] => [1][2][3]
1, 2, 3 => [1][2][3]
<1> has 1 inside. => <[1]> has[1]inside.

I appreciate your effort. I am hoping to find a regular expression that only changes numbers enclosed within square brackets.


OK.
-------------------------------------------------


1arryb
User

Feb 26, 2009, 1:58 PM


Views: 10065
Re: [KevinR] How to change [1,2,3] to [1][2][3]

Kevin,

or, more simply:

Code
my $x = "[3,4,5]\n[ 3 , 4 , 5 ]\n";  
$x =~ s/,/][/g;
$x =~ tr/ //d;
print $x;

It takes a second scan to trim the white space (should that prove necessary, but it's sure easier to understand Laugh

UPDATE:

D'oh! We both forgot the '1, 2, 3' case:

Code
my @xs = ('[3,4,5]', '[ 3 , 4, 5 ]', '3 , 4 , 5');  
for my $x (@xs) {
$x =~ s/[\[\] ]//g; # normalize all variants to '3,4,5'.
$x =~ s/,/][/g;
print "[$x]\n";
}


Cheers,

Larry


(This post was edited by 1arryb on Feb 26, 2009, 2:09 PM)