【问题标题】:VB.Net Regular Expressions - Extracting Wildcard ValueVB.Net 正则表达式 - 提取通配符值
【发布时间】:2011-07-15 17:01:22
【问题描述】:

我需要帮助从正则表达式匹配中提取通配符的值。例如:

正则表达式:“我喜欢 *”

输入:“我喜欢巧克力”

我希望能够从正则表达式匹配(或其他任何内容)中提取字符串“巧克力”。如果可能,我还希望能够从单个通配符匹配中检索多个通配符值。例如:

正则表达式:“我玩 * 和 *”

输入:“我会弹吉他和贝斯”

我希望能够同时提取“吉他”和“贝司”。有办法吗?

【问题讨论】:

    标签: regex vb.net string wildcard extraction


    【解决方案1】:

    通常,正则表达式利用组的概念。组由括号表示。

    所以我喜欢
    我会喜欢 (.) 吗? = 所有字符 * 表示与前面的字符一样多或没有前面的字符

    Sub Main()
        Dim s As String = "I Like hats"
        Dim rxstr As String = "I Like(.*)"
        Dim m As Match = Regex.Match(s, rxstr)
        Console.WriteLine(m.Groups(1))
    
    End Sub
    

    上面的代码将适用于具有 I Like 的字符串,并将在包含 ' ' as 后打印出所有字符。甚至匹配空白。

    您的第二种情况更有趣,因为第一个 rx 将匹配字符串的整个结尾,您需要更严格的内容。

    我喜欢 (\w+) 和 (\w+) :这将匹配 I Like then a space 和一个或多个单词字符,然后是 and 一个空格和 one or more word characters

    Sub Main()
    
        Dim s2 As String = "I Like hats and dogs"
        Dim rxstr2 As String = "I Like (\w+) and (\w+)"
        Dim m As Match = Regex.Match(s2, rxstr2)
        Console.WriteLine("{0} : {1}", m.Groups(1), m.Groups(2))
    End Sub
    

    要更完整地处理regex,请查看此站点,该站点有一个很棒的教程。

    【讨论】:

    • 正确。唯一需要注意的是外卡的贪婪。
    • 谢谢,顺便说一句,如果我打开了 IgnoreCase Regex 选项,有没有办法按照最初写入的方式返回通配符值?示例:“我喜欢 GeRmAnY”返回“GeRmAnY”
    【解决方案2】:

    这是我在 VBA 中的 RegexExtract 函数。它只会返回您指定的子匹配项(仅返回括号中的内容)。所以在你的情况下,你会写:

     =RegexExtract(A1, "I like (.*)")
    

    这是代码。

    Function RegexExtract(ByVal text As String, _
                          ByVal extract_what As String) As String
    
    Application.ScreenUpdating = False
    Dim allMatches As Object
    Dim RE As Object
    Set RE = CreateObject("vbscript.regexp")
    
    RE.Pattern = extract_what
    RE.Global = True
    Set allMatches = RE.Execute(text)
    RegexExtract = allMatches.Item(0).submatches.Item(0)
    Application.ScreenUpdating = True
    
    End Function
    

    这是一个允许您使用多个组一次提取多个部分的版本:

    Function RegexExtract(ByVal text As String, _
                          ByVal extract_what As String) As String
    
    Application.ScreenUpdating = False
    Dim allMatches As Object
    Dim RE As Object
    Set RE = CreateObject("vbscript.regexp")
    Dim i As Long
    Dim result As String
    
    RE.Pattern = extract_what
    RE.Global = True
    Set allMatches = RE.Execute(text)
    
    For i = 0 To allMatches.Item(0).submatches.count - 1
        result = result & allMatches.Item(0).submatches.Item(i)
    Next
    
    RegexExtract = result
    Application.ScreenUpdating = True
    
    End Function
    

    【讨论】:

      猜你喜欢
      • 2011-01-12
      • 1970-01-01
      • 2013-12-16
      • 1970-01-01
      • 2022-10-01
      • 2015-03-08
      • 1970-01-01
      相关资源
      最近更新 更多