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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-13 03:08:59

问题


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"

Dim 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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/7369543/using-vb-net-and-regex-to-find-string-inside-nested-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!