good chemistry is complicated, and a little bit messy -LW |
|
PerlMonks |
Re: string processing and regexp alternation...by danger (Priest) |
on Jan 27, 2002 at 13:17 UTC ( [id://141910]=note: print w/replies, xml ) | Need Help?? |
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:
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):
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:
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 Section
Seekers of Perl Wisdom
|
|