Regex 使用RegularExpression提取文本的特殊部分
我想使用正则表达式查找文本的特殊部分。例如,我有一个文本,如:KENNFELD TFSWNWRSA 4 我只想从本文中提取TFSWNWRSA 4,而不是KENNFELD,然后我想 我编写了这段代码,但它返回所有总计行:Regex 使用RegularExpression提取文本的特殊部分,regex,vba,Regex,Vba,我想使用正则表达式查找文本的特殊部分。例如,我有一个文本,如:KENNFELD TFSWNWRSA 4 我只想从本文中提取TFSWNWRSA 4,而不是KENNFELD,然后我想 我编写了这段代码,但它返回所有总计行: Dim fso As New FileSystemObject Dim ts As TextStream Dim Name As String Dim regx As New regexp Dim matchkennfeld As MatchCollection Dim matc
Dim fso As New FileSystemObject
Dim ts As TextStream
Dim Name As String
Dim regx As New regexp
Dim matchkennfeld As MatchCollection
Dim matchname As MatchCollection
Name = "D:/test_DC.txt"
'Set regexp = CreateObject("vbscript.regexp")
Set ts = fso.OpenTextFile(Name, ForReading)
Do While Not ts.AtEndOfStream
regx.Pattern = "KENNFELD\s+([A-Z 0-9]*)"
Set matchkennfeld = regx.Execute(ts.ReadLine)
If matchkennfeld.Count <> 0 Then
regx.Pattern = "([A-Z 0-9]*)"
' MsgBox matchkennfeld.Item(0)
Set matchname = regx.Execute(matchkennfeld.Item(0))
For Each Match In matchname
MsgBox Match
Next Match
End If
Loop
Dim fso作为新的FileSystemObject
将ts设置为文本流
将名称设置为字符串
Dim regx作为新的regexp
Dim matchkennfeld作为MatchCollection
将matchname设置为MatchCollection
Name=“D:/test\u DC.txt”
'Set regexp=CreateObject(“vbscript.regexp”)
设置ts=fso.OpenTextFile(名称,用于读取)
不要使用ts.AtEndOfStream
regx.Pattern=“KENNFELD\s+([A-Z 0-9]*)”
设置matchkennfeld=regx.Execute(ts.ReadLine)
如果matchkennfeld.计数为0,则
regx.Pattern=“([A-Z 0-9]*)”
'MsgBox matchkennfeld.Item(0)
设置matchname=regx.Execute(matchkennfeld.Item(0))
对于matchname中的每个匹配项
MsgBox匹配
下一场比赛
如果结束
环
你能帮我做这项工作吗?我的VB不好。但是我想说matchkennfeld将是一个数组,它包含匹配项和组(在其他语言中也是如此)。因此,当检查
项目(0)
时,我认为它与整个匹配匹配,而不是组匹配。因此,将其更改为使用子匹配项检查将解决此问题
Set matchname=regx.Execute(matchkennfeld(0).SubMatches(0))
可能会解决这个问题。你的意思是这样的?但是我有完整的文本,我只想要TFSWNWRSA 4请使用m
修饰符。从你的正则表达式看,你似乎只是从一个已知索引开始获取字符串的内容。难道你不能简单地使用MID函数并使用“KENNFELD”的长度作为起始索引吗?然后修剪结果。