【问题标题】:What is the better Regex Expression什么是更好的正则表达式
【发布时间】:2021-04-07 19:02:16
【问题描述】:

在我的程序中,我将发票 pdf 转换为文本。我正在寻找更好的正则表达式来解析字符串。我的转换结果是一个很长的字符串:

这是一个很长的字符串。发票总额:1,399.52 美元(续)很长的字符串。

我想解析出“Invoice Total:”之后的 1399.52。

这是我的第一次尝试:

    Dim text As String = "This is a very long string. Invoice Total: $1,399.52 Continuation of very long string."
    Dim re As Regex = New Regex("Invoice Total:\s*\$((\d|\.)*)")
    Dim m As Match = re.Match(text)
    For groupIdx As Integer = 0 To m.Groups.Count - 1
        Console.WriteLine("[{0}] = {1}", re.GetGroupNames(groupIdx), m.Groups(groupIdx).Value)

        If(groupIdx = 1) Then
            txtTotal.Text =  m.Groups(groupIdx).Value
        End If
    Next


Matches Found:
[0][0] = Invoice Total: $1,399.52
[0][1] = 1399.52
[0][2] = 0

代码有效,但我知道有更好的方法。

【问题讨论】:

  • 这看起来过于复杂了。尝试使用ideone.com/FmXPDC"Invoice Total:\s*\$(\d+(?:,\d+)*(?:\.\d+)?)" 正则表达式和m.Groups(1).Value.Replace(",","") 之类的方法来获取值。
  • 我也觉得Invoice Total:\s*\$((\d|\.)*)这个模式不会匹配Total: $1,399.52吧?
  • 为什么不Invoice Total: \$([\d,.]+) ?甚至Invoice Total: \$(\S+)。如果您知道$ 和数字末尾之间没有空格。
  • Dim decValue As Decimal = Decimal.Parse(Regex.Match[Input], "\$[\d,.]+\S").Value, NumberStyles.Currency, CultureInfo.GetCultureInfo("en-US"))

标签: regex vb.net


【解决方案1】:

你可以使用

Dim text As String = "This is a very long string. Invoice Total: $1,399.52 Continuation of very long string."
Dim re As Regex = New Regex("Invoice Total:\s*\$(\d+(?:,\d+)*(?:\.\d+)?)")
Dim m As Match = re.Match(text)
If m.Success Then
    Console.WriteLine(m.Groups(1).Value.Replace(",",""))
End If

请参阅 VB.NET demo.NET regex demo

注意:正则表达式可以根据实际情况进行简化。如果数字以第一个空格结尾,则可以仅使用

Invoice Total:\s*\$(\S+)

\S+ 将匹配一个或多个非空白字符。 正则表达式细节

  • Invoice Total: - 文字字符串(用作左侧上下文)
  • \s* - 零个或多个空格
  • \$ - 一个 $ 字符
  • (\d+(?:,\d+)*(?:\.\d+)?) - 捕获组 1:
    • \d+ - 一位或多位数字
    • (?:,\d+)* - 零个或多个逗号和一个或多个数字重复
    • (?:\.\d+)? - 可选出现一个句点和一个或多个数字。

请注意,可以仅使用 .Replace(",","") 删除逗号,或者您可以将提取编号转换为 decimal as shown by Jimi。请注意,您不能将不带逗号的数字提取到第 1 组,因为正则表达式从左到右连续解析字符串,并且在将(子)匹配值写入组时不能跳过字符。

【讨论】:

    猜你喜欢
    • 2015-06-05
    • 2011-06-15
    • 2015-06-09
    • 2011-08-08
    • 2020-07-24
    相关资源
    最近更新 更多