正则表达式,如何在不排除第一行的情况下将字符串匹配成两组

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

我尝试使用 (?P<Time>.+)\,\s(?P<Station>.+),但它没有捕获第一行。

示例字符串是:

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

在 regex101.com 测试:

您可以使用

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

查看 regex demo(切换到 单元测试,link 在左窗格中)。

详情:

  • ^ - 字符串开头
  • (?P<Time>[^,]+) - Time组:逗号以外的任何一个或多个字符
  • (?:,\s*(?P<Station>.+))? - 一个可选的序列
    • , - 逗号
    • \s* - 零个或多个空格
    • (?P<Station>.+) - 除换行字符外的一个或多个字符捕获到组“Station”
  • $ - 字符串结尾。

单元测试截图: