【问题标题】:Regex to ignore file path drive letter colon正则表达式忽略文件路径驱动器号冒号
【发布时间】:2013-11-19 05:28:03
【问题描述】:

我一直在测试这种模式:

Dim argumentsPattern As String = "/(?<var>.+):(?<val>.+)"

当字符串看起来像这样时效果很好:

/import-machinelist:Computers.txt

但是当字符串包含文件路径时,第二个冒号会破坏模式。

/import-machinelist:C:\Users\Administrator\Desktop\WinZooka\WinZooka\bin\Debug\computers.txt

如何修复忽略第二个冒号的模式?

这是我正在使用的 vb.net 代码。

Dim commandLineArgs() As String = Environment.GetCommandLineArgs()
        Dim argumentsPattern As String = "/(?<var>.+):(?<val>.+)"
        Dim localRegex = New Regex(argumentsPattern, RegexOptions.IgnoreCase)

        For Each arg As String In commandLineArgs

            If arg = "/?" Then

                MsgBox("Command line variables:" & Chr(13) & Chr(10) & _
                        "/username:JohnDoe" & Chr(13) & Chr(10) & _
                        "/password:Password1" & Chr(13) & Chr(10) & _
                        "/domain:lab.com" & Chr(13) & Chr(10) & _
                        "/import-machinelist:Computers.txt" & Chr(13) & Chr(10))

            Else
                Dim localMatch As Match = localRegex.Match(arg)
                If localMatch.Success Then

                    Select Case localMatch.Groups("var").ToString
                        Case "username"
                            txtUser.Text = localMatch.Groups("val").ToString
                        Case "password"
                            txtPass.Text = localMatch.Groups("val").ToString
                        Case "domain"
                            txtDomain.Text = localMatch.Groups("val").ToString
                        Case "import-machinelist"
                            importMachineList(localMatch.Groups("val").ToString)
                    End Select

                End If
            End If

        Next

任何帮助将不胜感激。

【问题讨论】:

  • 将分隔符从 : 切换到 = 会更好吗?

标签: regex vb.net


【解决方案1】:

只有当冒号后面没有\时,您才可以使用与冒号匹配的否定回溯:

\/(?<var>.+):(?!\\)(?<val>.+)

但不确定它是否涵盖了您的所有情况。

【讨论】:

    【解决方案2】:

    尝试将分隔符更改为分号 (;),然后您可以使用正则表达式或拆分参数,如下所示:

    带分号的正则表达式:

    Dim argumentsPattern As String = "/(?<var>.+);(?<val>.+)"
    

    用分号分割参数字符串:

    Dim argSplit As String() = arg.Split(';')
    
    Select Case argSplit(0)
        Case "username"
            txtUser.Text = localMatch.Groups("val").ToString
        Case "password"
            txtPass.Text = localMatch.Groups("val").ToString
        Case "domain"
            txtDomain.Text = localMatch.Groups("val").ToString
        Case "import-machinelist"
            importMachineList(localMatch.Groups("val").ToString)
    End Select
    

    【讨论】:

      【解决方案3】:

      您可以通过添加? 使第一个匹配组不贪婪:

      Dim argumentsPattern As String = "/(?<var>.+?):(?<val>.+)"
      

      这意味着它只捕获到第一个冒号之前。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-26
        • 2011-06-22
        • 2021-09-22
        • 2019-02-08
        相关资源
        最近更新 更多