Reputation: 23
I need to extract a word from incoming mail's body.
I used a Regex after referring to sites but it is not giving any result nor it is throwing an error.
Example: Description: sample text
I want only the first word after the colon.
Dim reg1 As RegExp
Dim M1 As MatchCollection
Dim M As Match
Dim EAI As String
Set reg1 = New RegExp
With reg1
.Pattern = "Description\s*[:]+\s*(\w*)\s*"
.Global = False
End With
If reg1.Test(Item.Body) Then
Set M1 = reg1.Execute(Item.Body)
For Each M In M1
EAI = M.SubMatches(1)
Next
End If
Upvotes: 1
Views: 602
Reputation: 626825
Note that your pattern works well though it is better written as:
Description\s*:+\s*(\w+)
And it will match Description
, then 0+ whitespaces, 1+ :
symbols, again 0 or more whitespaces and then will capture into Group 1 one or more word characters (as letters, digits or _
symbols).
Now, the Capture Group 1 value is stored in M.SubMatches(0)
. Besides, you need not run .Test()
because if there are no matches, you do not need to iterate over them. You actually want to get a single match.
Thus, just use
Set M1 = reg1.Execute(Item.body)
If M1.Count > 0 Then
EAI = M1(0).SubMatches(0)
End If
Where M1(0)
is the first match and .SubMatches(0)
is the text residing in the first group.
Upvotes: 1