正则expression式提取某些文本之前的数据

我有大量的文本文件,有一些我想要提取的数据。

正如你可以在截图中看到的 ,我想提取A040 excel列旁边的文件名。

A040之前,总是有三个空格和文本表单 (也在截图中)

每个文件有不同的数字,总是有字母A三位数字和文本表。 – >示例file upload:

我已经在VB与Excel中的东西,但它不工作。

Dim cell As Range Dim rng As Range Dim output As String Set rng = ws.Range("A1", ws.Range("A1").SpecialCells(xlLastCell).Address) For Each cell In rng On Error Resume Next output = ExtA(cell.Value) If Len(output) > 0 Then Range("B" & j) = output Exit For End If Next j = j + 1 ws.Cells.ClearContents 'Call DelConns strFileName = Dir 'next file Loop End Sub Function ExtA(ByVal text As String) As String 'REGEX Match VBA in excel Dim result As String Dim allMatches As Object Dim RE As Object Set RE = CreateObject("vbscript.regexp") RE.Pattern = "(?<=Sheet)[^Sheet]*\ Sheet" RE.Global = True RE.IgnoreCase = True Set allMatches = RE.Execute(text) If allMatches.Count <> 0 Then result = allMatches.Item(0).submatches.Item(0) End If ExtA = result End Function 

这似乎在您的示例工作。

 Option Explicit Function AthreeDigits(str As String) Dim n As Long, nums() As Variant Static rgx As Object, cmat As Object 'with rgx as static, it only has to be created once; beneficial when filling a long column with this UDF If rgx Is Nothing Then Set rgx = CreateObject("VBScript.RegExp") Else Set cmat = Nothing End If AthreeDigits = vbNullString With rgx .Global = False .MultiLine = True .Pattern = "\A[0-9]{3}[\s]{3}Sheet" If .Test(str) Then Set cmat = .Execute(str) AthreeDigits = Left(cmat.Item(0), 4) End If End With End Function 

你的意思是说在A040之后和“Sheet”之前有4个空格吗? 如果是这样,请尝试以下模式:

 .pattern = "(A\d\d\d)\s{3}Sheet" 

编辑:我以为你说了4个空格,但是你说了3.我的模式现在反映了这一点。 编辑2 :(我需要更多的咖啡!)将\ b更改为\ s。

在这里看到例子

"\s+[Aa]\d*\s+Sheet"
要么
\s+[Aa]\d*\s+(Sheet)
要么
[Aa]\d*\s+(Sheet)

演示
https://regex101.com/r/Qo8iUf/3

在这里输入图像描述

\s+匹配任何空格字符(等于[\r\n\t\f\v ]
+量词 – 匹配一次和无限次,尽可能多次
Aa匹配列表中的单个字符Aa (区分大小写)
\d*匹配一个数字(等于[0-9]
*量词 – 匹配零次和无限次,尽可能多次

在这里输入图像描述