简体   繁体   English

如何在C#中的逗号和换行符上拆分字符串?

[英]How do I split a string on both commas and newlines in c#?

I'm trying to split a string that can come in with either commas or newlines, based on an input from a textarea. 我正在尝试根据来自textarea的输入来拆分可以用逗号或换行符输入的字符串。 I'm not sure of the syntax to split this string in c#. 我不确定在c#中拆分此字符串的语法。 Currently I have: 目前我有:

string[] splitString = inputString.Split(','); //WORKS
//string[] splitString = inputString.Split(new string[] { ",","\r\n","\n" }, StringSplitOptions.None); //DOES NOT WORK

Since some text uses \\r for new line. 由于某些文本使用\\r作为新行。

You should use the code below and remove the empty entries to make the array cleaner. 您应该使用下面的代码并删除空条目以使阵列更整洁。

string[] splitString = inputString.Split(new string[] { ",", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);

or using Regex.Split . 或使用Regex.Split (This doesn't remove empty entries.) (这不会删除空条目。)

String[] splitString = Regex.Split(inputString, "[,\r\n]");

Update 更新资料

You can also use Regex.Split with empty entries removed, thanks to WiktorStribiżew 's comment. 由于WiktorStribiżew的评论,您还可以使用Regex.Split删除空条目。

The code below removes the empty entries which aren't in the beginning or end of the string. 下面的代码删除了不在字符串开头或结尾的空条目。

String[] splitString = Regex.Split(inputString, "[,\r\n]+");

To eliminate empty entries showing in the beginning or end of the line, use the code below. 要消除行开头或行末显示的空白条目,请使用下面的代码。

Regex.Split(Regex.Replace(inputString, "^[,\r\n]+|[,\r\n]+$", ""), "[,\r\n]+");

Regular Expression Language 正则表达式语言

If you want more informations about Regex , or how it works, you can look here for a quick reference. 如果您想了解有关Regex或其工作方式的更多信息,可以在此处查找快速参考。

您可以将Environment.NewLine传递到您的字符串数组中:

string[] splitString = inputString.Split(new string[] { ",", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM