+ Start a Discussion

regex for grabbing email address from a string

I wrote the following



Public Static String getEmailFromSubjecct(String Subject){ // First, instantiate a new Pattern object "MyPattern" String emailRegex = '(\\w+)@(\\w+\\.)(\\w+)(\\.\\w+)*'; Pattern MyPattern = Pattern.compile(emailRegex); // Then instantiate a new Matcher object "MyMatcher" Matcher MyMatcher = MyPattern.matcher(Subject); boolean hasMatch = MyMatcher.matches(); String match = MyMatcher.group(0); return match;


 the variable "hasMatches" returns "true" when I call this with


EmailTools.getEmailFromSubject('test@test.com is an email address');


but  the string "match" fails with "System.StringException: No match found"


I am lost here.  Why would the .matches() method return true if there are no matches?







Boolean found = MyMatcher.find();


before my call to the group() method seems to solve this issue.  Not sure why.

God thank you for posting this. I was pulling my hair out about why group() wasn't ever finding anything.

samba.gao@meginfo.com  verification not successfully.



The below code will work with addresses of type "samba.gao@meginfo.com" as well.


Please note that you'll need to use "myMatcher.find()" or else the use of myMatcher.group() will give an error message even thoug there is a match.


String text = 'Send email to my.email@mycompany.com';

String regex = '([a-zA-Z0-9_\\-\\.]+)@(((\\[a-z]{1,3}\\.[a-z]{1,3}\\.[a-z]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3}))';		
Pattern myPattern = Pattern.compile(regex );	
Matcher myMatcher = myPattern.matcher(text);

//The below code will give you my.email@mycompany.com in the debug log.		
if (myMatcher.find()) {