12

I am trying to get emails from a String which is like:

"*** test@gmail.com&&^ test2@gmail.com((& ";

private static Pattern p = Pattern.compile("(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)");

The code above can get one email.

How can I get all?

Michaël
  • 3,679
  • 7
  • 39
  • 64
Felix
  • 1,253
  • 7
  • 22
  • 41
  • You can use pattern class in java [see here][1] [1]: http://stackoverflow.com/questions/7899116/extracting-names-and-email-address-from-string-with-regex – PSR Mar 29 '13 at 13:00
  • see here http://stackoverflow.com/questions/7899116/extracting-names-and-email-address-from-string-with-regex – PSR Mar 29 '13 at 13:01
  • I'm not sure the `+` char is allowed in emails. – sp00m Mar 29 '13 at 13:04

2 Answers2

46

try

    String s = "*** test@gmail.com&&^ test2@gmail.com((& ";
    Matcher m = Pattern.compile("[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+").matcher(s);
    while (m.find()) {
        System.out.println(m.group());
    }
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • 1
    Does not work for me – JPM Jul 19 '17 at 21:31
  • 2
    Solution at this link is perfect, https://handyopinion.com/utility-method-to-get-all-email-addresses-from-a-string-in-java/ – Asad Ali Choudhry Nov 10 '19 at 06:58
  • This is a Kotlin function using the answer: @JvmStatic fun extractEmails(text: String): MutableList { val list = mutableListOf() val m: Matcher = Pattern.compile("[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+").matcher(text) while (m.find()) { list.add(m.group()) } return list } – fvildoso Mar 13 '21 at 23:37
0

Just remove the ^ and $ anchors.

sp00m
  • 47,968
  • 31
  • 142
  • 252