Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: simple regexp question

by jbert (Priest)
on Nov 21, 2007 at 10:25 UTC ( [id://652096]=note: print w/replies, xml ) Need Help??


in reply to simple regexp question

And to elaborate slightly on why the given solutions work, parens ( ) in a regexp capture their contents to the special variables $1, $2, ....

These are numbered according to the order of the capture groups (as ordered by their left hand paren).

You can use them (as shown) in the right-hand-side of a search and replace, but they're also valid perl variables which you can make use of after a substitution or ordinary match:

my $line = "furrfu"; $line =~ /(r+)/; print "$line contained ", length($1), " repeated 'r's\n";
Since regexp could in principle overwrite these global special variables, you should make use of them immediately after the regexp and/or save off their values into more appropriateley named vars. (e.g. if you call a subroutine, you don't know if that sub has done a regex and overwritten them).

Since parens are used for purposes other than grouping (e.g. to have alternating choices (foo|bar|baz), you can use a "non-capturing group", with (?:).

Search for 'captur' in perlre for more gory details.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (6)
As of 2024-04-19 12:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found