开发者

Using vb.net and RegEx to find string inside nested string

开发者 https://www.devze.com 2023-04-04 02:29 出处:网络
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

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()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号