jeudi 2 avril 2015

RegEx to extract email

I need to extract only the email from a spreadsheet in Excel. I've found some example VB code here on StackOverflow link , courtesy of Portland Runner.


I created an Excel module and it seems to be working fine, except. It only return the first uppercase character of the address in to cell and ignoring the email.


For example:



Text | Result
----------------------------------------|------------------------------
My email address is address@gmail.com | My email address is
Yes Address@gmail.com | Yes A


Below is the code I'm using:



Function simpleCellRegex(Myrange As Range) As String
Dim regEx As New RegExp
Dim strPattern As String
Dim strInput As String
Dim strReplace As String
Dim strOutput As String


strPattern = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"

If strPattern <> "" Then
strInput = Myrange.Value
strReplace = ""

With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With

If regEx.test(strInput) Then
simpleCellRegex = regEx.Replace(strInput, strReplace)
Else
simpleCellRegex = "Not matched"
End If
End If
End Function


I do not have enough experience with VB to really diagnose that might be happening here, hopefully someone will be able to spot what I'm doing wrong.


Edit


After exploring the code a bit further and changing the .IgnoreCase from false to true. I noticed that the code is working in reverse. It matches the emails correctly but the it would extract everything except the mail into the cell.


Aucun commentaire:

Enregistrer un commentaire