【问题标题】:Using regular expressions to get a word in between two Key words使用正则表达式在两个关键词之间获取一个词
【发布时间】:2009-07-27 19:44:05
【问题描述】:

我已经有一段时间没有使用正则表达式了,我希望我正在尝试做的事情是可能的。我有一个程序可以发送有关特定文件的自动响应,我想抓取两个我知道永远不会改变的单词之间的文本。在这个例子中,这些词是“关于”和“发送”

Dim subject As String = "Information regarding John Doe sent."
Dim name As String = Regex.IsMatch(subject, "")

所以在这种情况下,我希望能够只获得“John Doe”。我想出的每个正则表达式都包含“关于”和“发送”这两个词。如何使用这些词作为边界但不将它们包含在匹配中?

【问题讨论】:

    标签: c# .net asp.net vb.net regex


    【解决方案1】:

    假设"Information regarding ""sent."永远不变,可以使用捕获组获取"John Doe"

    ^Information regarding (.+) sent.$
    

    你这样使用它:

    Dim regex As New Regex("^Information regarding (.+) sent.$")
    Dim matches As MatchCollection = regex.Matches(subject)
    

    现在,它应该只匹配一次,你可以从匹配的 Groups 属性中获取组:

    For Each match As Match In matches  
      Dim groups As GroupCollection = match.Groups
      Console.WriteLine(groups.Item(1).Value) // prints John Doe
    Next
    

    【讨论】:

    • 最后一行应该是 Console.WriteLine(groups.Item(1).Value) - 第 0 组是整个匹配,而第 1 组是第一个捕获(带括号的)组。
    【解决方案2】:

    您的正则表达式基本上应该如下所示:

    .*regarding (.+) sent.*
    

    您要查找的数据将在第一个捕获变量中(Perl 中为 $1)。

    【讨论】:

      【解决方案3】:

      虽然匹配所有组是一种方法,但我会使用两个不匹配的组和一个名为 froup 的组,这样它就只会返回您想要的组。这会给你正则表达式:

      (?:regarding )(?<filename>.*)(?: sent)
      

      这将使您能够从组中调用文件名,例如

      Dim rx As New Regex("(?:regarding )(?<filename>.*)(?: sent)", _
                 RegexOptions.Compiled )
      Dim text As String = "Information regarding John Doe sent."
      Dim matches As MatchCollection = rx.Matches(text)
      'The lazy way to get match, should print 'John Doe'
      Console.WriteLine( matches[0].Groups.Item("filename").Value ) 
      

      在 msdn 网站 here 上找到了一个很好的 Regex 资源

      【讨论】:

        猜你喜欢
        • 2020-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多