Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Matching patterns with or

by corfuitl (Sexton)
on Jun 19, 2018 at 16:06 UTC ( [id://1216950]=perlquestion: print w/replies, xml ) Need Help??

corfuitl has asked for the wisdom of the Perl Monks concerning the following question:

Dear Perlmonks

Applying the following code

while ($_ =~ /({\d+})/ || $_ =~ /({\w+>)/ || $_ =~ /(<\w+})/){ print "$1\n"; }

to this text

This is <i} a test {i> sentence <i}

I get

{i>    <i}    <i}

Is there any way to get them according to their occurrence? So,

<i}  {i>  <i}

Thanks

Replies are listed 'Best First'.
Re: Matching patterns with or
by Eily (Monsignor) on Jun 19, 2018 at 16:34 UTC

    There's no way that code gives that output. Since $_ never changes, the middle condition is always true so $1 is always {i>. Also you print \n but your output is on one line...

    Your code is missing the /g option, which would make each search start from the position of the previous match. And if you want to search for all alternatives at once, rather than one first, then the second and so on you can replace the test (/(A)/g || /(B)/g || /(C)/g) by (/(A|B|C)/g) (regexes work on $_ by default, so you can ommit the $_ =~). See perlretut for more information on regexes.

    Also { } are special characters in regexes, it works in your case, but you should escape them to avoid trouble.

      Thanks,

      I updated the code as you mentioned and it works :)

      Once again, thank you for your time.

Re: Matching patterns with or
by AnomalousMonk (Archbishop) on Jun 19, 2018 at 18:32 UTC

    Another way:

    c:\@Work\Perl\monks>perl -wMstrict -le "$_ = 'The <A} test {B> sentence <C} foo {42} bar {D> baz' +; ;; while (m{ \G .*? ({\d+} | {\w+> | <\w+}) }xmsg) { printf qq{'$1' }; } " '<A}' '{B>' '<C}' '{42}' '{D>'

    Update 1: Changed example code slightly so that the test sentence includes all sub-patterns.

    Update 2: On second thought, the  \G .*? part of this regex contributes nothing in this particular application; leaving it out does not change the behavior of the match. As Eily wrote, the  /(A|B|C)/g pattern is all you need.


    Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2024-04-25 07:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found