仅提取包含8位数字且后面不包含字符(.,@)的数字



我使用一个函数从字符串中提取数字,条件是该数字包含8位且不包含字符(.,@(
它使用8位数字,但如果数字后面跟着字符(.,@(,它也会提取该数字,而不是必需的
这是我的字符串11111111 12345678.1 11111112 11111113,在没有12345678.1的情况下,预期输出为111111111111111121211111113
我试图使用负的Lookaheadd{8}(?!.,@),但它没有用
谢谢大家的帮助

Function Find8Numbers(st As String) As Variant
Dim regex As New RegExp
Dim matches As MatchCollection, mch As match

regex.Pattern = "d{8}"      'Look for variable length numbers only
regex.IgnoreCase = True
regex.Global = True
regex.MultiLine = True

If (regex.Test(st) = True) Then
Set matches = regex.Execute(st)   'Execute search
For Each mch In matches
Find8Numbers = LTrim(Find8Numbers) & " " & mch.value
Next
End If
End Function

根据您的问题和当前的尝试,您确实可以使用regex:

Function Find8Numbers(st As String) As String
With CreateObject("vbscript.regexp")
.Pattern = "(?:^|s)(d{8})(?![.,@d])"
.Global = True
If .Test(st) Then
Set Matches = .Execute(st)
For Each mch In Matches
Find8Numbers = LTrim(Find8Numbers & " " & mch.submatches(0))
Next
End If
End With
End Function

调用方式:

Sub Test()
Dim s As String: s = "11111111  12345678.1 11111112 11111113"
Debug.Print Find8Numbers(s)
End Sub

打印:

11111111 11111112 11111113

使用的模式:

(?:^|s)(d{8})(?![.,@d])

查看在线演示

  • (?:^|s)-VBA中没有查找,因此使用了非捕获组来匹配起始行锚点空白
  • (d{8})-捕获组中正好有8位数字
  • (?![.,@d])-断言位置的否定前瞻后面没有任何给定字符,包括数字

对于一个相当简单的模式,我不确定您是否需要Regex。你可以使用VBA解决方案:

Public Function Find8Numbers(str As String) As String
Dim c As String, c1 As String
Dim i As Long, numStart As Long
Dim isNumSeq As Boolean
Dim result As String

If Len(str) < 8 Then Exit Function

For i = 1 To Len(str)
c = Mid(str, i, 1)
If i = Len(str) Then
c1 = ""
Else
c1 = Mid(str, i + 1, 1)
End If
If c >= "0" And c <= "9" Then
If isNumSeq Then
If i - numStart + 1 = 8 Then
If c1 <> "." And c1 <> "," And c1 <> "@" Then
If result <> "" Then result = result & " "
result = result & Mid(str, numStart, 8)
isNumSeq = False
End If
End If
Else
If i > Len(str) - 8 + 1 Then Exit For
isNumSeq = True
numStart = i
End If
Else
isNumSeq = False
End If
Next
Find8Numbers = result
End Function

最新更新