简体   繁体   English

正则表达式,匹配3组,第二和第三可能是可选的

[英]Regex, match 3 groups, second and third might be optional

Given I have a string: Sebastian New York Canal st : Dinner at 5 c'clock. 给我一个字符串: Sebastian New York Canal st : Dinner at 5 c'clock. Where: 哪里:

  • Sebastian is first match 塞巴斯蒂安是第一场比赛
  • New York Canal st second (might be many spaces and dots) 纽约运河st秒(可能有很多空格和圆点)
  • Dinner at 5 c'clock. 5点钟的晚餐。 third (might be many spaces and dots) 第三(可能有很多空格和点)

between 2nd and 3rd group I have colon to separate those groups. 在第二和第三组之间,我用冒号将这些组分开。

I wrote regular expression: https://regex101.com/r/iI6kN8/1 我写了正则表达式: https : //regex101.com/r/iI6kN8/1

([A-Za-z0-9]+)?([A-Za-z0-9 ]+)?(:\ ([A-Za-z0-9'. ]+))

And it works when I have 3 groups: 当我有3个群组时,它会起作用:

在此处输入图片说明 在此处输入图片说明

but when I have: 但是当我有:

  • Sebastian New York Canal st

or 要么

  • Sebastian

Does not 才不是

Make the 3rd group optional: 将第三组设为可选:

([A-Za-z0-9]+)?([A-Za-z0-9 ]+)?(:\ ([A-Za-z0-9'. ]+))?

https://regex101.com/r/zW1oM6/2 https://regex101.com/r/zW1oM6/2

Try this regex 试试这个正则表达式

/^(\w+)(?:(.+?(?=:|$))\:?(.*)?)/m

See DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM