在 C# 中拆分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15421651/
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-08-10 16:46:20  来源:igfitidea点击:

Splitting a string in C#

c#regexstringsplit

提问by user1875195

I am trying to split a string in C# the following way:

我正在尝试按以下方式在 C# 中拆分字符串:

Incoming string is in the form

传入字符串的形式

string str = "[message details in here][another message here]/n/n[anothermessage here]"

And I am trying to split it into an array of strings in the form

我正在尝试将其拆分为表单中的字符串数组

string[0] = "[message details in here]"
string[1] = "[another message here]"
string[2] = "[anothermessage here]"

I was trying to do it in a way such as this

我试图以这样的方式做到这一点

string[] split =  Regex.Split(str, @"\[[^[]+\]");

But it does not work correctly this way, I am just getting an empty array or strings

但它不能以这种方式正常工作,我只是得到一个空数组或字符串

Any help would be appreciated!

任何帮助,将不胜感激!

采纳答案by Guffa

Use the Regex.Matchesmethod instead:

改用该Regex.Matches方法:

string[] result =
  Regex.Matches(str, @"\[.*?\]").Cast<Match>().Select(m => m.Value).ToArray();

回答by p.s.w.g

The Splitmethod returns sub strings betweenthe instances of the pattern specified. For example:

Split方法返回指定模式实例之间的子字符串。例如:

var items = Regex.Split("this is a test", @"\s");

Results in the array [ "this", "is", "a", "test" ].

结果在数组中[ "this", "is", "a", "test" ]

The solution is to use Matchesinstead.

解决办法是Matches改用。

var matches =  Regex.Matches(str, @"\[[^[]+\]");

You can then use Linq to easily get an array of matched values:

然后,您可以使用 Linq 轻松获取匹配值的数组:

var split = matches.Cast<Match>()
                   .Select(m => m.Value)
                   .ToArray();

回答by Brian Surowiec

Instead of using a regex you could use the Splitmethod on the string like so

您可以Split像这样在字符串上使用该方法,而不是使用正则表达式

Split(new[] { '\n', '[', ']' }, StringSplitOptions.RemoveEmptyEntries)

You'll loose [and ]around your results with this method but it's not hard to add them back in as needed.

你会失去[]周围的结果与此方法,但它不是很难将其添加回去需要。

回答by Kenneth K.

Another option would be to use lookaround assertions for your splitting.

另一种选择是使用环视断言进行拆分。

e.g.

例如

string[] split = Regex.Split(str, @"(?<=\])(?=\[)");

This approach effectively splits on the void between a closing and opening square bracket.

这种方法有效地分割了右方括号和左方括号之间的空白。