查找文本中具有已知格式的未知字符串

时间:2018-08-29 09:43:48

标签: excel string vba

如何使用MS Excel中的公式查找格式为xx.xx.xx的字符串(可以是数字或字母)?

2 个答案:

答案 0 :(得分:4)

尝试

=MID(A1, SEARCH("??.??.??", A1), 8)

enter image description here

答案 1 :(得分:1)

这是一个可在工作表中用作用户定义函数的正则表达式。当前设置为每个单元格仅检索一个结果,但可以轻松扩展。

尝试regex here

Option Explicit
Public Sub TEST()
    Dim tests(), i As Long
    tests = Array("11.22.33 avx", "abc 11.22.33 cdvdsds", "111.22.33", "1.22.33", "11.22.33.22", "dd.dd.dd.dd", "dd.dd.dd")

    For i = LBound(tests) To UBound(tests)
        Debug.Print GetID(tests(i))
    Next
End Sub

Public Function GetID(ByVal inputString As String) As String
  With CreateObject("VBScript.RegExp")
            .Global = True
            .MultiLine = True
            .Pattern = "(?:^|[^.])\b((?:[A-Za-z0-9]{2}\.){2}[A-Za-z0-9]{2}\b)(?!\.)"
            If .TEST(inputString) Then
              GetID = .Execute(inputString)(0).submatches(0)
            Else
              GetID = vbNullString
            End If
  End With
End Function

感谢@RonRosenfeld从最初的恐怖中改进了正则表达式:

.Pattern = "(:?^|\s)([A-Za-z0-9][A-Za-z0-9]\.[A-Za-z0-9][A-Za-z0-9]\.[A-Za-z0-9][A-Za-z0-9]){1,8}(?=\s|$)"

.Pattern = "(?:^|[^.])\b((?:[A-Za-z0-9]{2}\.){2}[A-Za-z0-9]{2}\b)(?!\.)"

所有匹配项:

对于所有匹配项的逗号分隔列表,请按以下方式修改功能:

Public Function GetID(ByVal inputString As String) As String
    Dim matches As Object, total As Long, arr(), i As Long
    With CreateObject("VBScript.RegExp")
        .Global = True
        .MultiLine = True
        .Pattern = "(?:^|[^.])\b((?:[A-Za-z0-9]{2}\.){2}[A-Za-z0-9]{2}\b)(?!\.)"
        If .TEST(inputString) Then
            Set matches = .Execute(inputString): total = matches.Count - 1
            ReDim arr(0 To total)
            For i = 0 To total
                arr(i) = matches(i).Submatches(0)
            Next
            GetID = Join(arr, Chr$(44))
        Else
            GetID = vbNullString
        End If
    End With
End Function