Regex Group in Perl: how to capture elements into array from regex group that matches unknown number of/multiple/variable occurrences from a string?

前端 未结 9 2143
遇见更好的自我
遇见更好的自我 2020-12-04 10:10

In Perl, how can I use one regex grouping to capture more than one occurrence that matches it, into several array elements?

For example, for a string:



        
9条回答
  •  离开以前
    2020-12-04 10:40

    I've recently had to parse x509 certificates "Subject" lines. They had similar form to the one you have provided:

    echo 'Subject: C=HU, L=Budapest, O=Microsec Ltd., CN=Microsec e-Szigno Root CA 2009/emailAddress=info@e-szigno.hu' | \
      perl -wne 'my @a = m/(\w+\=.+?)(?=(?:, \w+\=|$))/g; print "$_\n" foreach @a;'
    
    C=HU
    L=Budapest
    O=Microsec Ltd.
    CN=Microsec e-Szigno Root CA 2009/emailAddress=info@e-szigno.hu
    

    Short description of the regex:

    (\w+\=.+?) - capture words followed by '=' and any subsequent symbols in non greedy mode
    (?=(?:, \w+\=|$)) - which are followed by either another , KEY=val or end of line.

    The interesting part of the regex used are:

    • .+? - Non greedy mode
    • (?:pattern) - Non capturing mode
    • (?=pattern) zero-width positive look-ahead assertion

提交回复
热议问题