正则expression式Excel中期问题

我本质上是试图提取使用正则expression式美元金额,但无法弄清楚如何提取美元金额,这可能会有所不同的数字。 下面是我想要提取的数量字段的一个例子,它总是在字段的中间:

 &ltfield1&GT05 /二千零十三分之十四</ FIELD1>&ltamount&gt3,100,000.00 </量>&ltfield3&gt026002561 </字段3>

我现在有什么: <amount>.*</amount> (这个结果不能得到我想要的)

对于这个领域,我只想提取310万个数字。 围绕美元数字的结构(类似于html)将始终如一。 任何帮助表示赞赏。

高强

既然你在Excel中做这个,你可能要考虑使用这个公式

=MID(B1,SEARCH("<amount>",B1)+8,SEARCH("</amount>",B1)-(SEARCH("<amount>",B1) + 8))

  • B1 =inputstring
  • +8补偿string<amount>的宽度
  • 列C显示使用的公式

在这里输入图像说明

正则expression式

如果你使用VBA和正则expression式,你可以使用正则expression式: <(amount)\b[^>]*>([^<]*)<\/\1>

在这里输入图像说明

这个VB.net的例子只是为了显示正则expression式如何填充在数量标签中find的每个美元值的组3。

 Imports System.Text.RegularExpressions Module Module1 Sub Main() Dim sourcestring as String = "<field1>05/14/2013</field1><amount>3,100,000.00</amount><field3>026002561</field3> <field1>05/14/2013</field1><amount>4,444,444.00</amount><field3>026002561</field3>" Dim re As Regex = New Regex("<(amount)\b[^>]*>([^<]*)<\/\1>",RegexOptions.IgnoreCase OR RegexOptions.Multiline OR RegexOptions.Singleline) Dim mc as MatchCollection = re.Matches(sourcestring) Dim mIdx as Integer = 0 For each m as Match in mc For groupIdx As Integer = 0 To m.Groups.Count - 1 Console.WriteLine("[{0}][{1}] = {2}", mIdx, re.GetGroupNames(groupIdx), m.Groups(groupIdx).Value) Next mIdx=mIdx+1 Next End Sub End Module $matches Array: ( [0] => Array ( [0] => <amount>3,100,000.00</amount> [1] => <amount>4,444,444.00</amount> ) [1] => Array ( [0] => amount [1] => amount ) [2] => Array ( [0] => 3,100,000.00 [1] => 4,444,444.00 ) ) 

使用Excel VBA提取您的捕获组。

VBA代码

 Function TestRegExp(ByVal myString As String, _ ByVal myPattern As String, _ Optional seperator As String = "") As String Dim objRegExp As RegExp Dim colMatches As MatchCollection Dim RetStr As String Set objRegExp = New RegExp objRegExp.Pattern = myPattern objRegExp.IgnoreCase = True objRegExp.Global = True seperator = "|" If (objRegExp.Test(myString) = True) Then Set colMatches = objRegExp.Execute(myString) For i = 0 To colMatches.Count - 1 For j = 0 To colMatches.Item(i).SubMatches.Count - 1 If (RetStr <> "") Then RetStr = RetStr & seperator & colMatches.Item(i).SubMatches.Item(j) Else RetStr = colMatches.Item(i).SubMatches.Item(j) End If Next Next Else RetStr = "No Match" End If TestRegExp = RetStr End Function 

高强
在Excel中testing这个function是:

 =TestRegExp(B2,"<amount>([^<]*)<\/amount>") 

单元格B2有你的文本:

 <field1>05/14/2013</field1><amount>3,100,000.00</amount><field3>026002561</field3> Output: 3,100,000 

要么

 <field1>05/14/2013</field1><amount>3,100,000.00</amount><field3>026002561</field3><amount>999</amount> Output: 3,100,000|999 

请注意:

  1. 使用.*? 而不是.* 。 这有助于解决多个数量标签问题,因为它由问号懒洋洋地parsing。 你可以在代码中select你的分隔符。
  2. 诀窍是使用子匹配来获取组