如何抓取介于 2 个字符串之间的字符串 [英] How to grab a string that is between 2 strings

查看:40
本文介绍了如何抓取介于 2 个字符串之间的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯了 VB6 使用 split 方法如下:

I was used to VB6 using the split method as the following:

Split(Split(strLOL,strCool)(1),strCOOL)(0)

通过这个,我能够抓取一个介于 2 个字符串之间的字符串.

With this i was able to grab a string that was between 2 strings for example.

"en_us":"hi",

strLOL 是例如:"en_US":"strCool",

strLOL was for example: "en_US":" and strCool was ",

所以它会抓取这两者之间的字符串.

So it would grab the string between those two.

如何在 VB.NET 中执行此操作?

How am i possible to do this within VB.NET?

编辑:让我说清楚."en_us":"hi", 是我在文本中的字符串文件...我有一个包含 "en_us":"hi", 的文本框,我想抓取

Edit: Let me set this straight. "en_us":"hi", is a string i have in a text file... I have a textbox that contains "en_us":"hi", and i want to grab everything between

  • "en_us":"
  • ",

所以想要的结果是:hi

推荐答案

让我说清楚."en_us":"hi", 是我在文本中的字符串文件...我有一个包含以下内容的文本框:"en_us":"hi", 我想抓取"en_us":"", 之间的所有内容,因此响应将是:hi

Let me set this straight. "en_us":"hi", is a string i have in a text file... I have a textbox that containts: "en_us":"hi", and i want to grab everything between "en_us":" and ", So the response would be: hi

您将使用 String.Substring 在 .NET 中,如果您想返回两个其他子字符串之间的字符串.您使用 String.IndexOf 找到子串的索引:

You would use String.Substring in .NET if you want to return a string between two other substrings. You use String.IndexOf to find the index of the substrings:

Dim str = IO.File.ReadAllText(pathToTextFile) '  "en_us":"hi",
Dim grabBetween1 = """en_us"":"""
Dim grabBetween2 = ""","
Dim indexOf = str.IndexOf(grabBetween1)

Dim result As String
If indexOf >= 0 Then ' default is -1 and indices start with 0
    indexOf += grabBetween1.Length ' now we look behind the first substring that we've already found
    Dim endIndex = str.IndexOf(grabBetween2, indexOf)
    If endIndex >= 0 Then
        result = str.Substring(indexOf, endIndex - indexOf)
    Else
        result = str.Substring(indexOf)
    End If
End If

结果是:hi

如果你坚持使用 String.Split 或者你想看看 .NET 中的等价物,这里是:

If you insist on using String.Split or you want to see what is the equivalent in .NET, here it is:

Dim result = str.Split({grabBetween1}, StringSplitOptions.None)(1).Split({grabBetween2}, StringSplitOptions.None)(0)

也返回 hi.但是,这样可读性较差,更容易出错,而且效率较低.

which also returns hi. However, that is less readable, much more error-prone, and less efficient.

这篇关于如何抓取介于 2 个字符串之间的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆