12

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

"*** [email protected]&&^ [email protected]((& ";

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?

3

2 Answers 2

46

try

 String s = "*** [email protected]&&^ [email protected]((& "; 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()); } 
Sign up to request clarification or add additional context in comments.

3 Comments

Does not work for me
Solution at this link is perfect, handyopinion.com/…
This is a Kotlin function using the answer: @JvmStatic fun extractEmails(text: String): MutableList<String> { val list = mutableListOf<String>() 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 }
0

Just remove the ^ and $ anchors.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.