php - Regular Expression optional matches without greediness -


for educational purposes, i'm trying match name, phone , email of following content:

john +1 288298600 john@site.com  billy  mike +1 768397651 mike@site.com  patrick +2 938468172  jack jack@site.com 

i know how emails , phones that, want here different.

i want get, each name (john, billy, mike, patrick, jack) phone (if any) , email (if any). matches like

'john',    '+1 288298600',  'john@site.com' 'billy',   '',             '' 'mike',    '+1 768397651', 'mike@site.com' 'patrick', '+2 93868172',  '' 'jack',    '',             'jack@site.com' 

notice if there no corresponding info (phone or email) matches empty string. how can that?

my attempt: ([a-za-z0-9]+)(?:.*?(\+.*?)|.*?)(?:.*?(.*?\@site.com)|.*?)

anyone can guide me in right direction?

don't try using multiple matches, won't lead anywhere. instead, match 1 time per entry, , use capturing groups extract relevant data.

here's example (with mx flags):

^(?<name>[\p{l}\h]+$)\r (?:(?<phone>^\+[\d\h]+$)\r)? (?<mail>^.+?@.+?\..+)? 

demo

the first line matches name, followed newline. second line optional - matches phone number, followed newline. third line, optional, matches mail.

you may refine subpatterns if needed, picked seemed work input data.


Comments