如何在正则表达式匹配中也获取字符串的其余部分?

How to grab the rest of the string too in the regex matches?

我有以下字符串:

this is a test string user:testuser,anotheruser hashtag:peach,phone,milk site:youtube.com,twitter.com flair:bobby

目前,正则表达式 ([^:\s]+):([^:\s]+) 匹配所有中间带有冒号的过滤器(用户、主题标签、站点、风格)。我怎样才能将剩余的 "this is a test string" 部分作为另一场比赛?

演示:

https://regex101.com/r/L0T2GJ/11

您可以添加一个替代项,以尽可能少地匹配从字符串开头到第一个键后跟冒号的任何 0+ 个字符:

^.*?(?=\s+[^:\s]+:)|([^:\s]+):([^:\s]+)
^^^^^^^^^^^^^^^^^^^

regex demo

详情

  • ^ - 字符串的开头 -.*? - 除换行字符外的任何 0+ 个字符,尽可能少
  • (?=\s+[^:\s]+:) - 正前瞻确保在当前位置的右侧,有
    • \s+ - 1+ 个空格
    • [^:\s]+ - 除了 : 和空格
    • 之外的 1+ 个字符
    • : - 冒号