Is there a Perl equivalent of Python's re.findall/re.finditer (iterative regex results)?

后端 未结 3 534
渐次进展
渐次进展 2020-12-18 04:28

In Python compiled regex patterns have a findall method that does the following:

Return all non-overlapping matches of pattern in string, as a list

相关标签:
3条回答
  • 2020-12-18 04:33

    Use the /g modifier in your match. From the perlop manual:

    The "/g" modifier specifies global pattern matching--that is, matching as many times as possible within the string. How it behaves depends on the context. In list context, it returns a list of the substrings matched by any capturing parentheses in the regular expression. If there are no parentheses, it returns a list of all the matched strings, as if there were parentheses around the whole pattern.

    In scalar context, each execution of "m//g" finds the next match, returning true if it matches, and false if there is no further match. The position after the last match can be read or set using the pos() function; see "pos" in perlfunc. A failed match normally resets the search position to the beginning of the string, but you can avoid that by adding the "/c" modifier (e.g. "m//gc"). Modifying the target string also resets the search position.

    0 讨论(0)
  • 2020-12-18 04:44

    Nice beginner reference with similar content to @kyle's answer: Perl Tutorial: Using regular expressions

    0 讨论(0)
  • 2020-12-18 04:54

    To build on Chris' response, it's probably most relevant to encase the //g regex in a while loop, like:

    my @matches;
    while ( 'foobarbaz' =~ m/([aeiou])/g )
    {
        push @matches, $1;
    }
    

    Pasting some quick Python I/O:

    >>> import re
    >>> re.findall(r'([aeiou])([nrs])','I had a sandwich for lunch')
    [('a', 'n'), ('o', 'r'), ('u', 'n')]
    

    To get something comparable in Perl, the construct could be something like:

    my $matches = [];
    while ( 'I had a sandwich for lunch' =~ m/([aeiou])([nrs])/g )
    {
        push @$matches, [$1,$2];
    }
    

    But in general, whatever function you're iterating for, you can probably do within the while loop itself.

    0 讨论(0)
提交回复
热议问题