Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Matching patterns with or

by corfuitl (Sexton)
on Jun 19, 2018 at 16:06 UTC ( #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 (Bishop) 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
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? | Other CB clients
Other Users?
Others rifling through the Monastery: (2)
As of 2021-03-07 02:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favorite kind of desktop background is:











    Results (119 votes). Check out past polls.

    Notices?