简体   繁体   中英

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. Where:

  • Sebastian is first match
  • New York Canal st second (might be many spaces and dots)
  • Dinner at 5 c'clock. 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

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

And it works when I have 3 groups:

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

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

Try this regex

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

See DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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