我需要仅从Excel中的电子表格中提取电子邮件。我在StackOverflow上找到了一些示例VB代码link,礼貌Portland Runner。正则表达式提取电子邮件
我创建了一个Excel模块,它似乎工作正常,除了。它只会将地址的第一个大写字母返回到单元格,并忽略电子邮件。
例如:
Text | Result
----------------------------------------|------------------------------
My email address is [email protected] | My email address is
Yes [email protected] | Yes A
下面是我使用的代码:
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
我没有用VB足够的经验确实诊断出可能发生在这里,希望有人会能够发现我做错了什么。
工作守则
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-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-zA-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 = True
.Pattern = strPattern
End With
If regEx.Test(strInput) Then
Set matches = regEx.Execute(strInput)
simpleCellRegex = matches(0).Value
Else
simpleCellRegex = "Not matched"
End If
End If
End Function
如果您在RegEx模式掩码中未指定大写和小写,但希望捕获不区分大小写的结果,那么不应将'.IgnoreCase = False'设为'.IgnoreCase = True'? – Jeeped 2015-04-01 13:56:26
相关:http://stackoverflow.com/q/201323/1188513 – 2015-04-01 14:05:35
你说的话有道理,但改变'.IgnoreCase = False'对结果没有影响。 – 2015-04-01 14:05:39