正则expression式在前瞻中find空格或逗号

我环顾四周,但找不到我所需要的答案。 提前道歉,因为我目前正在教自己的正则expression式(在Excel中使用VB),我认为我有一个语法问题。

我想要的是:
要查找文本文档中的所有5位数字,请将它们与date关联起来,并将其打印到Excel电子表格中。

我得到的是:
每个date的每个集合的单个实例。

我认为是错误的:
我的正则expression式模式的定义。 我想find一个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 

对于一个正则expression式,匹配五个数字,后跟空格或逗号,请尝试:

 \d{5}(?=[ ,]) 

或者如果你真的想要任何空格字符:

 \d{5}(?=[\s,]) 

注意前视空间。 \ s,你使用的将匹配任何空白字符,但那些不仅包括空间

在你的正则expression式中,你使用

 (?=([\s]*)|[,]) 

因此,首先你要预见一个空格字符出现零次或多次 – 因为字符可能经常出现次,你可能不符合你的期望。

关于你的代码:

 oRegEx.IgnoreCase = True 

是无关的,但你需要添加

 oRegEx.Global = True 

以收集所有的比赛。

你的正则expression式find所有的5位数字(和5位数字)将是

 oRegEx.Pattern = "\b\d{5}\b" 

\b是一个单词边界, \d{5}匹配5个数字

你可以在这里testing一下