[Israel.pm] A regexp question

Yosef Meller mellerf at netvision.net.il
Sun May 16 10:22:25 PDT 2004

Hash: SHA1

Ishay Inbar wrote:
| Hi,
| This is a simple regexp I thought should work, and for some reason it
| I have a MAC address from a machine, which is mostly 8 couples of
[a-f][A-F][0-9] separated with "-" or ":" sign. For example:
| 00:E0:18:A8:39:B6.
| In some platforms, though, in case the left char in a couple is zero,
you just get the left value, for example from Solaris:
| 8:0:20:9f:22:78, where the first and the second couples start with 0.
| So I need to get 16 chars string, but in order not to loose data I
need to first fill the couples, and then remove the : or  sign.
| What I did was:
| my $zero = '0';
| $mac =~ s/(^|[^0-9A-Fa-f])([0-9A-Fa-f])([^0-9A-Fa-f])/$1$zero$2$3/g;
| For some reason this didn't work, and only replaced the first couple
with the missed value. A simple solution was:
| while ($mac =~
s/(^|[^0-9A-Fa-f])([0-9A-Fa-f])([^0-9A-Fa-f])/$1$zero$2$3/g) {}
| Can someone tell me why the global flag didn't work in this situation ?

Because after each match in the g' match, the position in the string is
moved after the last charachter matched, which is a [:-], and now your
regex can't match this as the first in the match. It's looking for (I'm
cutting down):


but he has a string that starts with a digit. A more elaborate example:

1) 8:0:20:9f:22:78
- -----^ We are here
2) "8:" matched, continuing with 0:20:9f:22:78. Can we match anything
starting with [:-] ? Nope.

What you need is a lookahead regex, that matches something without
advancing the position in the string: ([:-])([a-f0-9])(?=[:-])

The group with the ?= will be matched but not included in the match.
See also 'perldoc perlre ' under "Extended Patternd".

I hope this helps,

- --
perl -e'$b=unpack"b*",pack"H*","59dfce2d6b1664d3b26cd9969503";
Version: GnuPG v1.2.4 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org


More information about the Perl mailing list