Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: conditional match in regex

by jryan (Vicar)
on Nov 04, 2002 at 23:00 UTC ( [id://210330]=note: print w/replies, xml ) Need Help??


in reply to conditional match in regex

Well, here's how I would do it; this regex will populate $1 with the sigil, and $2 with the name if it is a variable like "$foo"; in the "<foo>" case, $1 will be undef and $2 will contain the name.

/ ^ # start (?:([\$\@\*\%])|<) # leading sigil or < (\w+) # name (?(?{$1}) |> ) # if there was a leading sigil, match nothing; # otherwise, match > $ # end /x;

Another way might be to use this one:

/ ^ # start ([\$\@\*\%<]) # sigil (\w+) # name (?(?{$1 eq '<'}) >| ) # if the sigil is a '<', match the end; # otherwise match nothing $ # end /x;

This is different in that in the "<foo>" case, $1 will be '<'.

In either case, theres no real reason to capture $3, since there is only one possibility that it could be(>), and you will know if the possibility is true or not depending on $1.

Replies are listed 'Best First'.
Re: Re: conditional match in regex
by petral (Curate) on Nov 05, 2002 at 01:23 UTC
    This also seems to work (at least in perl 5.6.1):
    / ^ ( [\$%@*] | (<) ) ( .* ) (? (2) > ) # ( (2) stands for $2 (the (<) above)) $ /x;


      p
      Yes, that will work, but yours has the problem that it creates $1, $2, and $3. I wanted to limit the regular expression so that $1 = type, and $2 = name.
        Right, this way $1 = type and $3 = name.  Oh well...

          p
Re: Re: conditional match in regex
by John M. Dlugosz (Monsignor) on Nov 05, 2002 at 16:31 UTC
    Thanks, that example of using code in a regex is exactly what I was wondering.

    The perlre page states that (?{ code }) is always successful, but also says that it may be used in a conditional match.

    So I'm guessing that if used alone, the code has side-effects only and always succeeds. But if used as the condition of a (?(condition)yes-pattern[|no-pattern]), then it does indeed use the result as the condition.

      Yep, you got it.

Log In?
Username:
Password:

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

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

    No recent polls found