2010/01/20

Perl regular expression tip: return all the matched things


Perl的正则表达式异常强悍,介绍一个不太引人注意但是又非常有用的功能:那就是返回所有匹配到的内容:“使用 //g 匹配”。 这时 $var =~ /regex/g 将会返回一个array,里面有所有匹配到的内容。如果在正则表达式中定义了group,就返回所有的groups;如果没有定义group,就返回所有匹配到的内容。
In list context, //g returns a list of matched groupings, or if there are no groupings, a list of matches to the whole regexp. So if we wanted just the words, we could use

        @words = ($x =~ /(\w+)/g);  # matches,
                                    # $word[0] = 'cat'
                                    # $word[1] = 'dog'
                                    # $word[2] = 'house'
需要注意,需要在一个 list context。说简单一点,就像上面的例子做就好。把匹配的结果赋值给一个array。

没有评论:

BlockChain 相关电子书

@copyright of Sam Chadwick   - https://thehub.thomsonreuters.com/groups/bitcoin/blog/2017/09/10/blockchain-paper Blockchain Papers A c...