我正在使用Excel VBA中的Microsoft正则表达式引擎。虽然我目前有一个可以工作的模式,但我对正则表达式很陌生,我需要扩展它,但我遇到了困难。以下是我的代码:
Sub ImportFromDTD()
Dim sDTDFile As Variant
Dim ffile As Long
Dim sLines() As String
Dim i As Long
Dim Reg1 As RegExp
Dim M1 As MatchCollection
Dim M As Match
Dim myRange As Range
Set Reg1 = New RegExp
ffile = FreeFile
sDTDFile = Application.GetOpenFilename("DTD Files,*.XML", , _
"Browse for file to be imported")
If sDTDFile = False Then Exit Sub '(user cancelled import file browser)
Open sDTDFile For Input Access Read As #ffile
Lines = Split(Input$(LOF(ffile), #ffile), vbNewLine)
Close #ffile
Cells(1, 2) = "From DTD"
J = 2
For i = 0 To UBound(Lines)
'Debug.Print "Line"; i; "="; Lines(i)
With Reg1
'.Pattern = "(\<\!ELEMENT\s)(\w*)(\s*\(\#\w*\)\s*\>)"
.Pattern = "(\<\!ELEMENT\s)(\w*)(\s*\(\#\w*\)\s*\>)"
.Global = True
.MultiLine = True
.IgnoreCase = False
End With
If Reg1.Test(Lines(i)) Then
Set M1 = Reg1.Execute(Lines(i))
For Each M In M1
sExtract = M.SubMatches(1)
sExtract = Replace(sExtract, Chr(13), "")
Cells(J, 2) = sExtract
J = J + 1
'Debug.Print sExtract
Next M
End If
Next i
Set Reg1 = Nothing
End Sub
目前,我正在对这样一组数据进行匹配:
<!ELEMENT DealNumber (#PCDATA) >
我需要提取Dealnumber,但现在,我需要在数据中添加另一个匹配项,就像这样:
<!ELEMENT DealParties (DealParty+) >
提取Dealparty,但不包括圆括号和加号。
我一直在使用这个作为参考,它非常棒,但我还是有点困惑。如何在Microsoft Excel中使用正则表达式(Regex)在单元格和循环中
编辑
我遇到了几种新的情况需要匹配。
Extract Deal
<!ELEMENT Deal (DealNumber,DealType,DealParties) >
Extract DealParty the ?,CR are throwing me off
<!ELEMENT DealParty (PartyType,CustomerID,CustomerName,CentralCustomerID?,
LiabilityPercent,AgentInd,FacilityNo?,PartyReferenceNo?,
PartyAddlReferenceNo?,PartyEffectiveDate?,FeeRate?,ChargeType?) >
Extract Deals
<!ELEMENT Deals (Deal*) >
sExtract = M.SubMatches(1)
处,如果我将光标悬停在上面,我会得到<无效的过程调用或参数>
和.pattern是<object variable or with block variable not set>
,我改变的唯一一件事就是模式。 - Matt WilliamsonPCDATA
,但事实并非如此。我已经更新了我的问题。 - Matt Williamson<!ELEMENT x (y)>
。您想得到什么?x
,y
还是两者都要? - Code Different