2009-07-27 107 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

相關問題