如何使用Regex从一个字符串(通常为“12X4321”)中提取12X4321这样的组?

cqoc49vn  于 2023-10-22  发布在  其他
关注(0)|答案(1)|浏览(94)

我使用如下模式从以下示例的WBS编号中提取三组标识符:

12B4321, 11.X.1111, M.O085C.11.X.1111,  M.O085C.11.X.1111.D2, M.O085C.23.B.0004.D2, M.O085C.23.BX.0004.D2, M.O053C.7I.F.0053.D2, M.O053C.8D.S.0001.D2, M.O053C.8I.S.0009.D2, M.O053C.8I.S.0009.D2"

我的模式是:(\d{2})([a-zA-Z])(\d{4})|(\d[a-zA-Z])\.?([a-zA-Z])\.?(\d{4})|(\d{2})\.?([a-zA-Z])\.?(\d{4})
除了第一个例子“12B4321”之外,所有的例子都可以用这个模式。当我在Regex101中测试该模式时,它可以工作,但是当我在MySQL中运行它时,第一个示例失败了。
有人能帮帮我吗?你可能已经意识到了,我是个新手。
在我得到不同的字符串部分之后,我将它们组合成我在查询中使用的形式“12.B.4321
我使用的代码示例如下:

Private Sub WBStest()
    Dim regEx As Object
    Dim WBSParts() As String
    Dim Inputstr() As String
    Dim SStr As String

    Inputstr = Split("12X4321, 13.X.6945, M.O085C.11.X.3576, MO085C11X6464D2, M.O085C.23.B.0004.D2, M.O085C.23.BX.0004.D2, M.O053C.7I.F.0053.D2, M.O053C.8D.S.0001.D2, M.O053C.8I.S.0009.D2, M.O053C.8I.S.0009.D2", ", ")
        
    Set regEx = CreateObject("VBScript.RegExp")
        With regEx
        For i = 0 To UBound(Inputstr)
        tbSøkProsjekt.Value = Inputstr(i)
            SStr = ""
            .Global = True
            .MultiLine = True
            .IgnoreCase = True
            .pattern = "(\d[0-9a-zA-Z])\.?([a-zA-Z])\.?(\d{4})"
            If .test(Inputstr(i)) Then
                WBSParts = Split(.Execute(Inputstr(i)).Item(0).Value, ".")
                If UBound(WBSParts) > 0 Then
                    SStr = WBSParts(0) & "." & WBSParts(1) & "." & WBSParts(2)
                End If
                Debug.Print Inputstr(i) & ": " & SStr
            End If
        Next
        End With
    Set regEx = Nothing
End Sub
bmvo0sr5

bmvo0sr51#

用点连接子匹配得到12.B.4321。

Private Sub WBStest()

    Dim regEx As Object, WBSParts, Inputstr() As String
    Dim s As String, i As Long
    
    Inputstr = Split("12X4321, 13.X.6945, M.O085C.11.X.3576, MO085C11X6464D2, " & _
        "M.O085C.23.B.0004.D2, M.O085C.23.BX.0004.D2, M.O053C.7I.F.0053.D2, " & _
        "M.O053C.8D.S.0001.D2, M.O053C.8I.S.0009.D2, M.O053C.8I.S.0009.D2", ", ")
    
    Set regEx = CreateObject("VBScript.RegExp")
    With regEx
        .Global = False
        .MultiLine = False
        .IgnoreCase = True
        .Pattern = "(\d[0-9A-Z])\.?([A-Z])\.?(\d{4})"

        For i = 0 To UBound(Inputstr)
            s = Trim(Inputstr(i))
            If .test(s) Then
                Set WBSParts = .Execute(s)(0).submatches
                Debug.Print s, WBSParts(0) & "." & WBSParts(1) & "." & WBSParts(2)
            End If
        Next
    End With
    Set regEx = Nothing

End Sub

相关问题