2009-07-27 175 views
0

自从我使用正则表达式以来,我一直在等待一段时间,我希望我正在尝试做的事情是可能的。我有一个程序发送关于某个特定文件的自动回复,我希望能够抓住两个我知道永远不会改变的文字。在这个例子中的那些话是“关于”和“送”使用正则表达式获取两个关键词之间的关键词

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

因此,在这种情况下,我希望能够得到的只是“李四”。每个我正在提出的正则表达式都包含“关于”和“已发送”等字样。我怎样才能将这些词作为边界,但不包括在比赛中?

回答

3

假设"Information regarding ""sent."永远不会改变,你可以使用一个捕获组获得"John Doe"

^Information regarding (.+) sent.$ 

你使用这种方式:

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

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

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

最后一行应该是`Console.WriteLine(groups.Item(1).Value)` - 组#0是整个匹配,而组#1是第一个捕获(加括号)的组。 – 2009-07-28 02:20:30

0

你的正则表达式应该基本上是这样的:

.*regarding (.+) sent.* 

你正在寻找的数据将在第一个捕获变量(在Perl $ 1)。

0

虽然匹配所有组是一种做法,但我会使用两个不匹配的组和一个名为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

相关问题