Next | Regular Expression Mastery | 69 |

`/g`means to do the match repeatedlywith

`s///g`, replace all occurrences (non-overlapping)with

`m//g`, find all matches, starting each where the previous one finished

`m//g`in list context returns a list of all matching strings:

"Madagascar" =~ m/a./g; # returns ('ad', 'ag', 'as', 'ar')

Extract all the numerals from a string:

"12-345:6 78" =~ m/\d+/g; # returns ('12', '345', '6', '78')

Note that this does

*not*return`2`or`34`or`45`Each

`m//g`picks up where the previous match*ended*

Split a string into fixed-length substrings:

@substrings = "abcdefghijklmnopqrstuvwxyz" =~ /.{1,5}/g; # Yields ('abcde', 'fghij, 'klmno', 'pqrst', 'uvwxy', 'z')

Notice importance of greed here - what if we had used

`.{1,5}?`?To omit

`z`, use`.{5}`instead of`.{1,5}`

Next | Copyright © 2002 M. J. Dominus |