Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: regex for multiple capture within boundary

by ikegami (Patriarch)
on Jul 14, 2006 at 19:57 UTC ( #561313=note: print w/replies, xml ) Need Help??


in reply to regex for multiple capture within boundary

my @nums = $x =~ /(\S+)/g;
or
my @nums = split(' ', $x);

Update: Oops, misread. How about

# @nums = ('1', '11', '2', '22', '222', '3', '33'); my @nums = $x =~ /(\d+)/g;

or

# @nums = (['1', '11'], ['2', '22', '222'], ['3', '33']); my @nums = map { [ /(\d+)/g ] } $x =~ /(\S+)/g;

I'm not clear on which one you want.

Update: Ah! Now I understand! How did I miss that?

# @nums = ('2', '22', '222'); my @nums = ($x =~ /\s(\S+)/)[0] =~ /(\d+)/g;

or

# @nums = ('2', '22', '222'); my @nums = (split(' ', $x, 3))[1] =~ /(\d+)/g;

Replies are listed 'Best First'.
Re^2: regex for multiple capture within boundary
by johngg (Canon) on Jul 16, 2006 at 22:14 UTC
    I think I understand what is going on in the first of your updated solutions but if I change it to read

    my @nums = ($x =~ /\s(\S+)/)[1] =~ /(\d+)/g;

    expecting output of

    3 33

    it doesn't work unless I also make the first match global like this

    my @nums = ($x =~ /\s(\S+)/g)[1] =~ /(\d+)/g;

    I think this is because the round brackets around the match put the match into list context and the [0] subscript grabs the first elements of the match; however, since the match is non-global there will only ever be one element in the list and trying to get more will not work. If we want a second or subsequent element we must make the match global to capture more than one element.

    Have I understood this correctly or am I completely missing the point?

    Cheers,

    JohnGG

      That's exactly it (although there could be 0 elements if the match fails).

      my @nums = ($x =~ /\s(\S+)/)[0] =~ /(\d+)/g;
      could also be written as
      my @nums = ($x =~ /\s(\S+)/ ? $1 : undef) =~ /(\d+)/g;

      If you're going to use /g, drop the \s:

      # @nums = ('3', '33'); my $word = 2; my @nums = ($x =~ /(\S+)/g)[$word] =~ /(\d+)/g;

      or use split:

      # @nums = ('3', '33'); my $word = 2; my @nums = (split(' ', $x))[$word] =~ /(\d+)/g;

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (3)
As of 2022-09-28 00:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer my indexes to start at:




    Results (124 votes). Check out past polls.

    Notices?