使用 vb.net 和 RegEx 在嵌套字符串中查找字符串

发布于 2024-12-03 18:31:39 字数 549 浏览 1 评论 0原文

使用 VB.NET,有没有办法在 1 步中执行此 RegEx 调用...而不是 2-3 步?

我正在尝试查找单词“bingo”,或者 START 和 END 单词之间的任何内容,但是 然后里面还有FISH和CAKES字样。我的最终结果应该只是“宾果”。

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

随风而去 2024-12-10 18:31:39

不确定 VB.NET,但您可以使用以下正则表达式捕获内部“bingo”:

START.*FISH.*(bingo).*CAKES.*END

“Bingo”将成为该表达式的第一个(也是唯一一个)匹配项。

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.

恋你朝朝暮暮 2024-12-10 18:31:39

您可以使用lookahead和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()

但我认为使用捕获组更简单,如@Alaudo建议的:

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

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文