VBA正则表达式问题:如何从含Total的匹配中提取数值
VBA正则提取发票总金额问题
需求
- 将发票文本文件内容读取到变量中
- 提取发票中的总金额
- 文本中“总计”的表述有多种:
tot、total:、total €:、total amount:、total value等
示例文本
<etc> BTW-nr: 0071.21.210 B 08 KvK 27068921 TOTAL € 22.13 Maestro € 22.13 <etc>.
现有代码
Public Function parse(inpPat As String) 'get the text file content strFilename = "D:\temp\invoice.txt" Open strFilename For Input As #iFile strFileContent = Input(LOF(iFile), iFile) Close #iFile Set regexOne = New RegExp regexOne.Global = False regexOne.IgnoreCase = True regexOne.Pattern = inpPat Set theMatches = regexOne.Execute(strFileContent) 'show the matching strings For Each Match In theMatches res = Match.Value Debug.Print res Next End Function
遇到的问题
- 调用
parse "tot[\w]+.+(\\d+(\\.|,)\\d{2})"时,返回整个匹配内容TOTAL € 22.13,但仅需数值22.13 - 调用
parse "(?:(?!tot[\w]+.+))(\\d+(\\.|,)\\d{2})"时,错误匹配到0071.21,未关联Total相关内容
解决方案
1. 修正正则表达式
使用以下正则模式,精准匹配“总计”关键词并捕获金额数值:
\btot\w*.*?(\d+(?:[.,]\d{2}))
\btot\w*:匹配所有以tot开头的单词(结合IgnoreCase=True,兼容TOTAL、total、tot等写法).*?:非贪婪匹配关键词到金额间的任意内容,避免过度匹配(\d+(?:[.,]\d{2})):捕获金额数值,支持.或,作为小数分隔符,固定两位小数;(?:...)为非捕获分组,仅用于规则分组
2. 修改代码获取捕获组内容
现有代码仅输出整个匹配结果,需通过SubMatches获取捕获组的纯数值:
For Each Match In theMatches ' 第一个捕获组即为目标金额 res = Match.SubMatches(0) Debug.Print res Next
3. 完整调用示例
使用修正后的正则调用函数:
parse "\btot\w*.*?(\d+(?:[.,]\d{2}))"
执行后将直接输出22.13
补充优化
如果需要兼容带货币符号的场景(如€、$),可调整正则跳过货币符号:
\btot\w*.*?(?:[€$£])?\s*(\d+(?:[.,]\d{2}))
内容的提问来源于stack exchange,提问作者emphyrio
相关产品推荐
相关产品推荐

