Regex with possible empty matches and multi-line match

后端 未结 4 1118
猫巷女王i
猫巷女王i 2021-01-23 22:28

I\'ve been trying to \"parse\" some data using a regex, and I feel as if I\'m close, but I just can\'t seem to bring it all home.
The data that needs parsing gener

4条回答
  •  忘了有多久
    2021-01-23 22:51

    The following regex should work, but I'm not so sure anymore if it is the right tool for this:

    preg_match_all(
        '%^            # Start of line
        ([^:]*)        # Match anything until a colon, capture in group 1
        :\s*           # Match a colon plus optional whitespace
        (              # Match and capture in group 2:
         (?:           # Start of non-capturing group (used for alternation)
          .*$          #  Either match the rest of the line
          (?=          #  only if one of the following follows here:
           \Z          #  The end of the string
          |            #  or
           \r?\n       #  a newline
           [^:\n\\\\]* #  followed by anything except colon, backslash or newline
           :           #  then a colon
          )            #  End of lookahead
         |             # or match
          (?:          #  Start of non-capturing group (used for alternation/repetition)
           [^:\\\\]    #  Either match a character except colon or backslash
          |            #  or
           \\\\.       #  match any escaped character
          )*           #  Repeat as needed (end of inner non-capturing group)
         )             # End of outer non-capturing group
        )              # End of capturing group 2
        $              # Match the end of the line%mx', 
        $subject, $result, PREG_PATTERN_ORDER);
    

    See it live on regex101.

提交回复
热议问题