Search code examples
coldfusioncoldfusion-9

Find Email Address in a string - ColdFusion 9


I was wondering if coldfusion has a build-in function to find email addresses in a string.

I am trying to read through a query output ex. "John Smith jsmith@example.com" and get out only the email.

I did something like this in the past where I was counting the spaces of the string and after the second string i was wiping out all the characters on the left which it was keeping the email address alone.

Though this can work in my situation, it is not safe and almost guarantee bugs and misuse of data that may come in in a different format such as "John jsmith@example.com" which in this case I will wipe away all the information.


Solution

  • Regex is probably the easiest way. There is an ultimate regex for email that is quite large. This should cover most valid emails. This doesn't cover unicode for example. Note that the maximum TLD length is 63 (see this SO question & answer).

    <cfset string="some garbae@.ca garbage@ca.a real@email.com another@garbage whatever another@email.com oh my!">
    
    <cfset results = reMatchNoCase("[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,63}", string)>
    
    <cfdump var="#results#">