【问题标题】:VBA RegEx: How to find the first instance of a number after a specific string and ignore all other characters?VBA RegEx:如何在特定字符串之后找到数字的第一个实例并忽略所有其他字符?
【发布时间】:2020-11-05 00:35:17
【问题描述】:

在编写能够获取我想要的模式的代码时遇到问题。我希望能够获取我拥有的 .txt 文件中 5 Months 之后出现的第一个数字。如果还有其他字符 A-Z、括号、$、% 等,我想忽略它们。我不断收到 VBA 错误代码,例如 INVALID PROCEDURE CALL OR ARGUMENT

目前,我的代码如下所示:

Dim reg4 As Object: Set reg4 = CreateObject("vbscript.regexp")
 reg4.Pattern = "5 Months\s*([\d+]\.[\d+])\s*"
   Dim MCS As Object
    Set MCS = reg4.Execute(myText)
    **Dim Months5 As String: Months5 = MCS(0).submatches(0)** *the error stems from this line*

其中 mytext 是由文本文件中的内容组成的字符串。我的主要问题是这个文本文件并不总是采用标准化格式,所以当我想在“5 个月”之后提取第一个数字时,它会给我这个错误。

文本文件可能如下所示:

示例 1

5 个月

($) (%) (月) (%) (%) (%) ($) (月)

0.00 0.0000 0.000

或 示例 2

5 个月

0.00

0.000

0.000

在这两种情况下,理想情况下,我都可以提取整个形式的第一个数字“0.00”,同时忽略任何其他字符,例如 (%) 或 ($),如示例 1 所示。

我想问一下是否有人对如何重写模式语句有任何建议,以便它能够拾取第一个数字实例及其小数点后的数字?

非常感谢!

【问题讨论】:

  • 嗨,Daria,请在下面查看我的回答,如果您的问题得到解决,请告诉我。

标签: regex vba


【解决方案1】:

您的正则表达式与您显示的字符串不匹配。你可以使用

\b5 Months[\s\S]*?(\d+(?:\.\d+)?)

请参阅regex demo。详情:

  • \b - 单词边界
  • 5 Months - 文字文本
  • [\s\S]*? - 任何 0 个或更多字符,尽可能少
  • (\d+(?:\.\d+)?) - 捕获组 1:一位或多位数字后跟可选的 . 序列和一位或多位数字。

在 VBA 中测试运行:

Sub TestFn()
Dim reg4 As Object: Set reg4 = CreateObject("vbscript.regexp")
 reg4.Pattern = "\b5 Months[\s\S]*?(\d+(?:\.\d+)?)"
Dim myText As String
 myText = "5 Months" & vbCrLf & vbCrLf & "0.00"
Dim MCS As Object
Set MCS = reg4.Execute(myText)
Dim Months5 As String: Months5 = MCS(0).SubMatches(0)
Debug.Print (Months5)
End Sub

【讨论】:

    猜你喜欢
    • 2021-08-01
    • 1970-01-01
    • 2019-01-18
    • 2017-11-26
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    相关资源
    最近更新 更多