Extract email and name with regex

后端 未结 5 2064
醉酒成梦
醉酒成梦 2020-12-06 02:10

What would be the regular expressions to extract the name and email from strings like these?

johndoe@example.com
John 
John Doe &l         


        
相关标签:
5条回答
  • 2020-12-06 02:18

    The following regex appears to work on all inputs and uses only two capturing groups:

    (?:"?([^"]*)"?\s)?(?:<?(.+@[^>]+)>?)
    

    http://regex101.com/r/dR8hL3

    Thanks to @RohitJain and @burning_LEGION for introducing the idea of non-capturing groups and character exclusion respectively.

    0 讨论(0)
  • 2020-12-06 02:19

    use this regex "?([^"]*)"?\s*([^\s]+@.+)

    group 1 contains name

    group 2 contains email

    0 讨论(0)
  • 2020-12-06 02:22

    This way you can get with or without name, removing the quotes.

    \"*?(([\p{L}0-9-_ ]+)\"?)*?\b\ *<?([a-z0-9-_\.]+@[a-z0-9-_\.]+\.[a-z]+)>?
    
    0 讨论(0)
  • 2020-12-06 02:37

    You can try this (same code as yours but improved), but you need to check returned groups after matching because the email is either returned in group 2 or group 3, depending on whether a name is given.

    (?:("?(?:.*)"?)\s)?<(.*@.*)>|(.*@.*)
    
    0 讨论(0)
  • 2020-12-06 02:43
    (([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))
    

    https://regex101.com/r/pVV5TI/1

    0 讨论(0)
提交回复
热议问题