我确实环顾四周,但找不到能满足我需要的答案。提前道歉,因为我正在教自己正则表达式(在excel中使用VB),我认为我有语法问题。
我想要的是什么:
要查找文本文档中的所有5位数字,将它们与日期相关联,然后将它们打印到Excel电子表格中。
我得到的是什么:
每个日期的每个数字的单个实例。
我认为错了:
我的正则表达式模式定义。我想找一个5位数字,可以在数字后面加上逗号或空格。
oRegEx.Pattern = "\d{5}(?=([\s]*)|[,])"
我非常有信心这是问题所在,而且我也确信它本质上是语法上的,但我对此很新,我不知道我做错了什么。我在下面发布了我的整个代码。
Public Sub ParseMail()
Dim i As Integer
Dim x As Integer
Dim oFSO As Scripting.FileSystemObject
Dim oFile As Scripting.TextStream
Dim sHeaderDate As String
Dim sIDList As String
Dim sTemp As String
Dim oRegEx As VBScript_RegExp_55.RegExp
Dim oMatches As Object
Set oFSO = New Scripting.FileSystemObject
Set oFile = oFSO.OpenTextFile("C:\Users\source doc.txt", ForReading) 'Open the exported file. Change path as needed.
Set oRegEx = New VBScript_RegExp_55.RegExp 'Instantiate RegEx object
oRegEx.IgnoreCase = True
oRegEx.Pattern = "\d{5}(?=([\s]*)|[,])" 'Regular expression to identify 5 digit numbers... not working well."
i = 1 ' init variable to 1. This is the first row to start writing in spreadsheet.
Do While Not oFile.AtEndOfStream ' Read the file until it reaches the end.
sTemp = oFile.ReadLine 'Get the first line
'Debug.Print sTemp
If Left(sTemp, 5) = "Sent:" Then 'Look for the date in the header.
sHeaderDate = Mid(sTemp, 7) 'set this variable starting at pos 7 of this line.
'Debug.Print sHeaderDate
Else
'This is not the date header so start checking for IDs.
Set oMatches = oRegEx.Execute(sTemp)
If Not oMatches Is Nothing Then 'Find anything?
If oMatches.Count > 0 Then
For x = 0 To oMatches.Count - 1 'walk thru all found values and write to active spreadsheet.
ActiveSheet.Cells(i, 1).Value = sHeaderDate
ActiveSheet.Cells(i, 2).Value = oMatches(x)
i = i + 1
Next
End If
End If
End If
Loop
oFile.Close
Set oFile = Nothing
Set oFSO = Nothing
Set oRegEx = Nothing
End Sub
答案 0 :(得分:1)
对于匹配五位数后跟空格或逗号的正则表达式,请尝试:
\d{5}(?=[ ,])
或者如果你真的想要任何空格字符:
\d{5}(?=[\s,])
注意前瞻中的空格。您使用的\,将匹配任何空格字符,但这些字符不仅仅包含空格。
在你的正则表达式中,你使用
(?=([\s]*)|[,])
首先,你要预见一个出现零次或多次的空白字符 - 因为这个字符可能经常出现零次,你可能与你期望的不匹配。
关于你的代码:
oRegEx.IgnoreCase = True
无关紧要,但您需要添加
oRegEx.Global = True
以收集所有比赛。
答案 1 :(得分:1)