25. Perl Options - Global Searches and the Multi-Match Anchor
- In Perl, it is possible to do a global search using the "/g" modifier.
- This means that you can find all occurrences of a regex in a target.
For example:
#!/usr/bin/perl
$_ = "6756 This is a string that has a number 12345 and another number 67890 in it.";
while (m/([0-9]+)/g) {
print "$1\n";
}
gives:
6756
12345
67890
- Perl's Multi-Match anchor, "\G", allows you to specify the point where
the last match ended (or, if no match has as yet occurred, the beginning
of the target string.)
#!/usr/bin/perl
$_ = "6756 This is a string that has a number 12345 and another number 67890 in it.";
while (m/\G([0-9]+)/g) {
print "$1\n";
}
gives:
6756
- See how the "\G" forces the regex to start again at the end of the position
it last matched at, and so the regex cannot bump along to the next character?
|