Capture all text per group

Viewed 35

I have some data that looks like this:

DEC 12, 2020
incoming 192.168.0.5 10:30
outgoing 192.168.0.5 13:23
DEC 13, 2020
incoming 192.168.0.6 09:34
outgoing 192.168.0.6 14:12

I am trying to get the date and all data for that date into one grouping like so:

First match
Group 1 - DEC 12, 2020
Group 2 - incoming 192.168.0.5 10:30
          outgoing 192.168.0.5 13:23

Second match
Group 1 - DEC 13, 2020
Group 2 - incoming 192.168.0.6 09:34
          outgoing 192.168.0.6 14:12

I have tried this regex:

^([A-Z] \d+, \d{4})(.*)

The problem is, this reads all the way to the end instead of stopping at the next match (DEC 13, 2020) like so:

Group 1 - DEC 12, 2020
Group 2 - incoming 192.168.0.5 10:30
          outgoing 192.168.0.5 13:23
          DEC 13, 2020
          incoming 192.168.0.6 09:34
          outgoing 192.168.0.6 14:12

If I add the ? like so:

^([A-Z] \d+, \d{4})(.*?)

The I get only the dates.

First Match
Group 1 - DEC 12, 2020
Group 2 - white space

Second Match
Group 1 - DEC 13, 2020
Group 2 - white space

Can someone please tell me what I am missing? How can I get it to stop at the next match and not the end of the line or end of the text? All lines have a CRLF at the end. Thanks.

1 Answers

You can use

(?m)^([A-Z]{3} \d+, \d{4})((?:\r?\n(?![A-Z]{3} \d).*)*)

See the regex demo. Details:

  • (?m) - a RegexOptions.Multiline inline option
  • ^ - start of a line
  • ([A-Z]{3} \d+, \d{4}) - Group 1: three uppercase ASCII letters, space, one or more digits, a comma, a space and then four digits
  • ((?:\r?\n(?![A-Z]{3} \d).*)*) - Group 2: zero or more occurrences of
    • \r?\n - a CRLF or LF only line break sequence...
    • (?![A-Z]{3} \d) - that is not immediately followed with three uppercase ASCII letters, space, digit
    • .* - the rest of the line.

Output:

enter image description here

Related