Using VB.NET, Is there a way to do this RegEx call in 1 step... instead of 2-3?
I'm trying to find the word "bingo", or whatever is between the START and END words, but then also inside the inner FISH and CAKES words. My final results should be just "bingo".
Dim s1 As String = "START (random string) FISH bingo CAKES (random string) END"
Di开发者_如何学Cm m As Match
m = RegEx.Match(s1, "START\w*END")
If (m.Success) Then
Dim s2 As String = m.Groups(0).ToString()
m = RegEx.Match(s2, "FISH\w*CAKES")
if(m.Success) then
s2 = m.Groups(0).ToString()
m = RegEx.Match(s2, "bingo")
s2 = m.Group(0).ToString()
End If
End If
Not sure about VB.NET, but you can catch the inner "bingo" using the following RegExp:
START.*FISH.*(bingo).*CAKES.*END
"Bingo" will be then the first (and the only) match of this expression.
You can use lookahead and lookbehind:
Dim s1 As String = "START (random string) FISH bingo CAKES (random string) END"
Dim m As Match = RegEx.Match(s1, "(?<=\bSTART\b.*?\bFISH\s+)\w+(?=\s+CAKES\b.*?\bEND\b)")
Dim s2 as String = m.Value()
But I think it's simpler to use a capturing group as @Alaudo suggested:
Dim m As Match = RegEx.Match(s1, "\bSTART\b.*?\bFISH\s+(\w+)\s+CAKES\b.*?\bEND\b")
Dim s2 as String = m.Groups(1).Value()
精彩评论