There is the oft neglected $+ RE variable that refers to the highest numbered capturing parens that actually matched --- when the choice is limited as in your example it comes in handy:
my $pat = qr/\w+ ((w)hite|(b)lack)/; $_ = 'mostly black'; print "$1 starts with $+\n" if /$pat/; $_ = 'but some white spaces'; print "$1 starts with $+\n" if /$pat/;
Of course, when your choice revolves around multiple captures per alternation, as in /((w)hit(e)|(b)lac(k))/, then we are back to the same problem: do we have $2 and $3, or $4 and $5? $+ doesn't provide much help here. In some such cases, simply grep'ing the return values can give you what you want (the uncaptured parens would be undefined):
my $pat = qr/\w+ ((w)hit(e)|(b)lac(k))/; $_ = 'mostly black'; my($word, $first, $last) = grep defined $_, /$pat/; print "$word starts with $first and ends with $last\n" if $word; $_ = 'but some white spaces'; ($word, $first, $last) = grep defined $_, /$pat/; print "$word starts with $first and ends with $last\n" if $word;
But that can break down if you want to iterate over a /match/g in scalar context. In that case, you might formulate a quickie routine that returned only the successfully matched subgroups (in order) along the lines of:
my $pat = qr/\w+ ((w)hit(e)|(b)lac(k))/; $str = 'mostly black but some white spaces'; while ($str =~ /$pat/g) { my @m = get_captures($str); print "$m[1] starts with $m[2] and ends with $m[3]\n"; } sub get_captures { map { defined $+[$_] ? substr($_[0],$-[$_],$+[$_]-$-[$_]) :() } 0..$#+; }
Another possibility is that you may be using regular expressions when some other function is more appropriate --- getting the first or last character from a string (that you've already captured) can be done with substr as previously mentioned.
In reply to Re: string processing and regexp alternation...
by danger
in thread string processing and regexp alternation...
by princepawn
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |