C# string.split - 通过多个字符分隔符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1254577/
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
string.split - by multiple character delimiter
提问by
i am having trouble splitting a string in c# with a delimiter of "][".
我在用“][”分隔符分割 c# 中的字符串时遇到问题。
For example the string "abc][rfd][5][,][."
例如字符串“abc][rfd][5][,][.”
Should yield an array containing;
abc
rfd
5
,
.
应该产生一个包含的数组;
abc
rfd
5
,
.
But I cannot seem to get it to work, even if I try RegEx I cannot get a split on the delimiter.
但我似乎无法让它工作,即使我尝试 RegEx 我也无法在分隔符上进行拆分。
EDIT: Essentially I wanted to resolve this issue without the need for a Regular Expression. The solution that I accept is;
编辑:基本上我想在不需要正则表达式的情况下解决这个问题。我接受的解决方案是;
string Delimiter = "][";
var Result[] = StringToSplit.Split(new[] { Delimiter }, StringSplitOptions.None);
I am glad to be able to resolve this split question.
我很高兴能够解决这个分裂的问题。
采纳答案by Marc Gravell
To show both string.Split
and Regex
usage:
显示string.Split
和Regex
用法:
string input = "abc][rfd][5][,][.";
string[] parts1 = input.Split(new string[] { "][" }, StringSplitOptions.None);
string[] parts2 = Regex.Split(input, @"\]\[");
回答by SwDevMan81
string tests = "abc][rfd][5][,][.";
string[] reslts = tests.Split(new char[] { ']', '[' }, StringSplitOptions.RemoveEmptyEntries);
回答by Christopher Klewes
Regex.Split("abc][rfd][5][,][.", @"\]\]");
回答by seabass2020
Another option:
另外一个选项:
Replace the string delimiter with a single character, then split on that character.
用单个字符替换字符串分隔符,然后在该字符上拆分。
string input = "abc][rfd][5][,][.";
string[] parts1 = input.Replace("][","-").Split('-');