Beefy Boxes and Bandwidth Generously Provided by pair Networks
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??


in reply to string processing and regexp alternation...

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://141910]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2024-04-18 15:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found