string 如何使用多字符分隔符拆分字符串并保持分隔符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1211848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:30:14  来源:igfitidea点击:

How to split a string using a multiple character separator and maintain separator

vb.netstring

提问by Tanner

Using VB.NET - I have a string:

使用 VB.NET - 我有一个字符串:

"##RES00012##Some value ##RES00034##Another value"

That I want to split using the "##RES"as a separator to:

我想使用"##RES"作为分隔符来拆分:

"##RES00012## Some value"and "##RES00034## Another value"

"##RES00012## Some value""##RES00034## Another value"

The string.splitfunction doesn't seem to offer an overload to split on multiple characters or array of characters and maintain the seperator, which is required for functional purposes.

string.split函数似乎没有提供重载来拆分多个字符或字符数组并维护分隔符,这是功能性目的所必需的。

I'm looking at simply searching for indexOf("##res")and using string manipulation to do this unless I'm missing something obvious? I've searched SO for a solution but unable to find anything that actually does what I'm after.

我只是在寻找indexOf("##res")并使用字符串操作来执行此操作,除非我遗漏了一些明显的内容?我已经搜索了一个解决方案,但无法找到任何真正符合我要求的东西。

The following is the closest i've found: how-do-i-split-a-string-by-a-multi-character-delimiter-in-c

以下是我发现的最接近的: how-do-i-split-a-string-by-a-multi-character-delimiter-in-c

回答by Fredrik M?rk

Splitting on multiple characters is not that tricky; there are overloads on the String.Split method that does that:

拆分多个字符并不是那么棘手;String.Split 方法有重载,可以做到这一点:

Dim input As String = "##RES00012## Some value ##RES00034## Another value"
Dim parts As String() = input.Split(New String() {"##RES"}, StringSplitOptions.RemoveEmptyEntries)

This will give you an array with two elements:

这将为您提供一个包含两个元素的数组:

"00012## Some value "
"00034## Another value"

However, the separator is left out. This is not overly tricky though; it should be prepended to each of the elements (except the first one if the string does not start with the separator):

但是,分隔符被排除在外。不过,这并不过分棘手。它应该放在每个元素之前(如果字符串不以分隔符开头,则第一个除外):

Dim input As String = "##RES00012## Some value ##RES00034## Another value"
Dim parts As String() = input.Split(New String() {"##RES"}, StringSplitOptions.RemoveEmptyEntries)

For i As Integer = 0 To parts.Length - 1
    If i > 0 OrElse input.StartsWith("##RES") = True Then
        parts(i) = "##RES" & parts(i)
    End If
Next

回答by user2979918

Just use Microsoft.VisualBasic.Strings.Split():

只需使用Microsoft.VisualBasic.Strings.Split()

Dim inputs As String = "first value##second value##third value"
Dim parts As String() = Strings.Split(inputs,"##")