Search code examples
regexcapturing-group

Regex, how to match string into two groups without excluding the first line


I tried using (?P<Time>.+)\,\s(?P<Station>.+), but it did not capture the first line.

The sample strings aree:

9:21:13 AM
9:21:29 AM, TS729
9:21:33 AM, TS729

Tested at regex101.com:

enter image description here


Solution

  • You can use

    ^(?P<Time>[^,]+)(?:,\s*(?P<Station>.+))?$
    

    See the regex demo (switch to Unit Tests, the link is in the left pane).

    Details:

    • ^ - start of string
    • (?P<Time>[^,]+) - Time group: any one or more chars other than a comma
    • (?:,\s*(?P<Station>.+))? - an optional sequence of
      • , - a comma
      • \s* - zero or more whitespaces
      • (?P<Station>.+) - one or more chars other than line break chars captured into Group "Station"
    • $ - end of string.

    Unit tests screenshot:

    enter image description here