- 论坛徽章:
- 0
|
回复 1# jinger18
Grouping Matching
From a regular-expression point of view, there is no difference between except, perhaps, that the former is slightly clearer.
$string =~ /(\S+)\s+(\S+)/;
and
$string =~ /\S+\s+\S+/;
However, the benefit of grouping is that it allows us to extract a sequence from a regular expression. Groupings are returned as a list in the order in which they appear in the original. For example, in the following fragment we have pulled out the hours, minutes, and seconds from a string.
my ($hours, $minutes, $seconds) = ($time =~ m/(\d+) \d+) \d+)/);
As well as this direct method, matched groups are also available within the special $x variables, where x is the number of the group within the regular expression. We could therefore rewrite the preceding example as follows:
$time =~ m/(\d+) \d+) \d+)/;
my ($hours, $minutes, $seconds) = ($1, $2, $3);
When groups are used in substitution expressions, the $x syntax can be used in the replacement text. Thus, we could reformat a date string using this:
#!/usr/bin/perl
$date = '03/26/1999';
$date =~ s#(\d+)/(\d+)/(\d+)#$3/$1/$2#;
print "$date";
This will produce following result
1999/03/26 |
|