正则表达式仅返回七位数匹配

时间:2016-11-30 14:16:51

标签: regex excel-vba vba excel

我一直在尝试构建一个正则表达式,从字符串中提取一个7位数,但很难得到正确的模式。

示例字符串 - 1519641, 1528113, 1530212

返回示例 - Private Sub Extract7Digits() Dim regEx As New RegExp Dim strPattern As String Dim strInput As String Dim strReplace As String Dim Myrange As Range Set Myrange = ActiveSheet.Range("A1:A300") For Each c In Myrange strPattern = "\D(\d{7})\D" 'strPattern = "(?:\D)(\d{7})(?:\D)" 'strPattern = "(\d{7}(\D\d{7}\D))" strInput = c.Value With regEx .Global = True .MultiLine = True .IgnoreCase = False .Pattern = strPattern End With If regEx.test(strInput) Then Set matches = regEx.Execute(strInput) For Each Match In matches s = s & " Word: " & Match.Value & " " Next c.Offset(0, 1) = s Else s = "" End If Next End Sub

我在Excel中使用的代码是......

O1519641, O1528113T, O1530212

我已经尝试了该代码中的所有3种模式,但在使用"\D(\d{7})\D"时,我最终获得了()的回复。正如我现在所理解的那样()并不意味着什么,因为我存储匹配的方式,而我最初认为它们意味着表达式将返回 {{1>}内部的内容1}}。

我已经在http://regexr.com/上测试了一些内容,但我仍然不确定如何让它在WO1528113TB之内允许数字在字符串中,但只返回数字。我是否需要在RegEx的返回值上运行RegEx以在第二次排除字母?

1 个答案:

答案 0 :(得分:3)

我建议使用以下模式:

strPattern = "(?:^|\D)(\d{7})(?!\d)"

然后,您将能够通过(\d{7})访问捕获组#1内容(即使用正则表达式的match.SubMatches(0)部分捕获的文本),然后您可以检查哪个值最大

模式详情

  • (?:^|\D) - 匹配字符串开头(^)或非数字(\D
  • 的非捕获组(不创建任何子匹配)
  • (\d{7}) - 捕获第7组匹配7位数字
  • (?!\d) - 如果7个数字后面紧跟一个数字,则表示未通过比赛的否定前瞻。
相关问题