Email MailTo Links Regex

The following PeopleCode function finds email addresses (using a regular expression) and encloses them in a anchor hyperlink tag with a mail to link.

So for example the text:

test@peoplesoftwiki.com

Is replaced with the HTML:

<a href="mailto:test@peoplesoftwiki.com">test@peoplesoftwiki.com</a>

This is the PeopleCode function:

Constant &DOMAIN = "peoplesoftwiki.com";
 
Function ConvertEmailToLinks(&sInput As string) Returns string;
 
   Local JavaObject &jEmailRegex, &jEmailLinkRegex, &jInput;
   Local string &sHTML;
 
   &jEmailRegex = CreateJavaObject("java.lang.String", "[\w-.]+@(\w+.|)" | &DOMAIN);
 
   /* Replace the found match ($0 back reference) and enclose with a href mailto HTML tag */
   &jEmailLinkRegex = CreateJavaObject("java.lang.String", "<a href=""mailto:$0"">$0</a>");
 
   /* Store the text to be scanned for email addresses as a Java string object */
   &jInput = CreateJavaObject("java.lang.String", &sInput);
 
   /* Perform a replace all using the search email regex and the email link regex */
   &sHTML = &jInput.replaceAll(&jEmailRegex, &jEmailLinkRegex);
 
   Return &sHTML;
 
End-Function;

Remember to replace the constant, &DOMAIN with your organisation's base domain. Note that the email search regex in this example may need changing to cater for more specific email formats (see details below).

There are three key parts to this code.

The first part is the regular expression stored in the Java object &jEmailRegex which is converted to:

[\w-.]+@(\w+.|)peoplesoftwiki.com}}

This matches any email address that ends with your base domain (@peoplesoftwiki.com), or has one subdomain in it (@test.peoplesoftwiki.com) and is preceded by a word that can include a full stop or a hyphen in it (e.g. moc.ikiwtfoselpoep|nosrep-tset#moc.ikiwtfoselpoep|nosrep-tset or moc.ikiwtfoselpoep|nosrep.tset#moc.ikiwtfoselpoep|nosrep.tset). Note underscores are automatically catered for by the \w word match expression.

You should test this regex yourself using RegExr to ensure it matches the email address format used in your organisation as shown below:

regexr-email-address-test.png

Note the exception with the asterisk character (*) which only does a partial match for example.

The second key part of this code is the Java object &jEmailLinkRegex. This regex is what performs the conversion to a hyperlink:

<a href="mailto:$0">$0</a>

The $0 in this code is a back reference and evaluates to the result of the search regex (&jEmailRegex). So it is replaced by the email address found.

The third key part is the call to the replaceAll method. This is what causes all matching email addresses to be converted, taking the search regex (&jEmailRegex) and replacing it with the link regex (&jEmailLinkRegex).

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License