PDA

View Full Version : Question with regular expressions.


rq60
01-05-2003, 05:31 PM
I know if you have a string like $s = "43 23 34 54" and you want to loop through the sets you could do for split / /, $s.

But I've always been curious if there is a way to do it so that if the string was not seperated and looked like this $s = "43233454" to just have it loop through and each time grab the next 2 characters with regular expressions, or maybe some other method.

rq60
01-12-2003, 02:43 AM
Hrmmm, well I guess no one knows.. either that or it's IMPOSSIBLE! oh well

Mouldy_Goat
01-13-2003, 12:15 AM
Sure, you could just do something like this:
$string = "elephant";

while ($string =~ s/^(..?)//) {
print "$1\n";
}

The output is:
el
ep
ha
nt

I used a '?' after the second dot, so that if it was a word with an uneven number of characters, it would match just the one remaining character when it got to the end of the string. That is,

$string = "elephants";

while ($string =~ s/^(..)//) {
print "$1\n";
}
Would give:
el
ep
ha
nt

Whereas:
$string = "elephants";

while ($string =~ s/^(..?)//) {
print "$1\n";
}
Would give:
el
ep
ha
nt
s

Hope that helps a bit.