2011-07-15 61 views
0

我需要幫助從正則表達式匹配中提取通配符的值。例如:VB.Net正則表達式 - 提取通配符值

正則表達式:「我喜歡*」

輸入:「我喜歡巧克力」

我希望能夠從正則表達式匹配提取字符串「巧克力」 (或其他任何地方)。如果可能,我還希望能夠從單個通配符匹配中檢索多個通配符值。例如:

正則表達式:「我玩的是*和*」

輸入:「我彈吉他和低音」

我希望能夠提取既「吉他「和」低音「。有沒有辦法做到這一點?

回答

3

一般來說,正則表達式利用組的概念。組用括號表示。

所以我喜歡
將是我喜歡(
)。 =所有字符*意味着儘可能多的或沒有前面的字符

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 

上面的代碼將工作和字符串,有我喜歡的,包括「」作爲後會打印出所有的字符。甚至匹配白色空間。

你的第二種情況更有趣,因爲第一個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更完整的治療需要看看這個網站有一個很好的教程。

+0

權上。唯一需要注意的是外卡的貪婪。 –

+0

謝謝,順便說一下,如果我啓用了IgnoreCase Regex選項,是否有方法以最初編寫的方式返回通配符值?例如:「我喜歡GeRmAnY」返回「GeRmAnY」 – Walker

+0

它應該是默認的 – rerun

0

這是我在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