I'm trying to extract all four-digit numbers from a string in one fell swoop, but I can't seem to come up with the proper regexp. This is my first time using /g in a match so maybe there's a trick I'm missing.
For example, the string
"1111 2222aa3333 444 55555555 6666 7777-8888"
should yield
1111, 2222, 3333, 6666, 7777, 8888.
Here's one attempt that I thought had a reasonable chance.
- - - - - #!/usr/bin/perl -w my $foo = "1111 2222aa3333 444 55555555 6666 7777-8888"; my @a = ($foo =~ m'[\D^](\d{4})[\D$]'g);
The first character class requires that the number is preceeded by a non-digit character. (The ^ character has no special meaning in a character class.) Since the first number is not preceeded by anything, 1111 is not matched.
I suppose you meant to do:
my @a = ($foo =~ m'(?:\D|^)(\d{4})(?:\D|$)'g);
which gives
1111:3333:6666:8888
but that's not what you want either. The reason why e.g. 2222 is not matched is that the space after 1111 is included in the first match, so the second attempt to match starts at the first '2'...
You'd better use extended patterns, i.e. zero-width assertions:
my @a = $foo =~ /(?<!\d)\d{4}(?!\d)/g;
Read about extended patterns in "perldoc perlre".
-- Gunnar Hjalmarsson Email: http://www.gunnar.cc/cgi-bin/contact.pl
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>