[英]Split string by (') and Spaces but keep any space character between two consecutive (')
[英]Splitting a string with a space/two spaces after the character
考虑一些字符串,假设它们包含“Wxxx”形式的“键”,其中 x 是 0-9 的数字。 每一个都可以只包含一个,也可以包含多个,用“,”隔开,后跟两个空格。 例如:
W123
W432
W546, W234, W167
包含多个“键”的那些需要被拆分成一个数组。 所以,上面例子中的最后一个应该被拆分成这样的数组: {"W546", "W234", "W167"}
。
作为一种快速解决方案,我String.Split
,但据我所知,它可以采用一个字符,例如 ','。 问题是它会返回一个这样的数组: {"W546", " W234", " W167"}
。 可以使用Substring
删除从第二个开始的所有数组条目中的两个空格,但是有更好的解决方案吗?
就上下文而言,这些值保存在电子表格中,并假定已经过数据验证以确保“键”由逗号后跟两个空格分隔。
while ((ws.Cells[row,1].Value!=null) && (ws.Cells[row,1].Value.ToString().Equals("")))
{
// there can be one key, or multiple keys separated by ','
if (ws.Cells[row,keysCol].Value.ToString().Contains(','))
{
// there are multiple
// need to split the ones in this cell separated by a comma
}
else
{
// there is one
}
row++;
}
您可以只指定','
和' '
作为分隔符和RemoveEmptyEntries
。
使用您的单键示例和包含多个键的字符串,您可以完全相同地处理它们并获取单个键的列表:
List<string> cells = new List<string>() { "W123", "W432", "W546, W234, W167" };
List<string> keys = new List<string>();
foreach (string cell in cells)
{
keys.AddRange(cell.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries));
}
Split
可以处理无需拆分的字符串, AddRange
将接受您的单键以及多键拆分结果。
首先消除多余的空间(使用Replace()
),然后使用 split。
var input = "W546, W234, W167";
var normalized = input.Replace(", ",",");
var array = normalized.Split(',');
这样,您处理逗号后跟一个空格的方式与处理逗号的方式完全相同。 如果可能有两个空格,您也可以替换它:
var input = "W546, W234, W167";
var normalized = input.Replace(" "," ").Replace(", ",",");
var array = normalized.Split(',');
您可以使用旧的最爱——正则表达式。
这里有两种口味“Loop”或“LINQ”。
static void Main(string[] args)
{
var list = new List<string>{"W848","W998, W748","W953, W9484, W7373","W888"};
Console.WriteLine("LINQ");
list.ForEach(l => TestSplitRegexLinq(l));
Console.WriteLine();
Console.WriteLine("Loop");
list.ForEach(l => TestSplitRegexLoop(l));
}
private static void TestSplitRegexLinq(string s)
{
string pattern = @"[W][0-9]*";
var reg = new Regex(pattern);
reg.Matches(s).ToList().ForEach(m => Console.WriteLine(m.Value));
}
private static void TestSplitRegexLoop(string s)
{
string pattern = @"[W][0-9]*";
var reg = new Regex(pattern);
foreach (Match m in reg.Matches(s))
{
Console.WriteLine(m.Value);
}
}
只需将Console.Write
替换为您想要的任何内容:例如。 myList.Add(m.Value)
。
您将需要添加 NameSpace: using System.Text.RegularExpressions;
在 .NET fiddle 中尝试这个之后,我想我可能有一个解决方案:
// if there are multiple
string keys = ws.Cells[row,keysCol].Value.ToString();
// remove spaces
string keys_normalised = keys.Replace(" ", string.Empty);
Console.WriteLine("Checking that spaces have been removed: " + keys3_normalised + "\n");
string[] splits = keys3_normalised.Split(',');
for (int i = 0; i < splits.Length; i++)
{
Console.WriteLine(splits[i]);
}
这会在控制台中产生以下输出:
Checking that spaces have been removed: W456,W234,W167
W456
W234
W167
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.