【发布时间】: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"))