C#RegEx模式将字符串拆分为2个字符的子字符串
我试图找出一个正则表达式,用来将字符串拆分为2个字符的子字符串 假设我们有以下字符串:C#RegEx模式将字符串拆分为2个字符的子字符串,c#,regex,C#,Regex,我试图找出一个正则表达式,用来将字符串拆分为2个字符的子字符串 假设我们有以下字符串: string str = "Idno1"; string pattern = @"\w{2}"; 使用上面的模式将得到“Id”和“no”,但它将跳过“1”,因为它与模式不匹配。我希望得到以下结果: string str = "Idno1"; // ==> "Id" "no" "1 " string str2 = "Id n o 2"; // ==> "Id", " n", " o", " 2"
string str = "Idno1";
string pattern = @"\w{2}";
使用上面的模式将得到“Id”和“no”,但它将跳过“1”,因为它与模式不匹配。我希望得到以下结果:
string str = "Idno1"; // ==> "Id" "no" "1 "
string str2 = "Id n o 2"; // ==> "Id", " n", " o", " 2"
Linq可以简化代码。版本有效 想法:我有一个
chunkSize
=2作为您的要求,然后,获取索引(2,4,6,8,…)处的字符串以获取字符块,并将它们连接到字符串
public static IEnumerable<string> ProperFormat(string s)
{
var chunkSize = 2;
return s.Where((x,i) => i % chunkSize == 0)
.Select((x,i) => s.Skip(i * chunkSize).Take(chunkSize))
.Select(x=> string.Join("", x));
}
在这种情况下,Linq真的更好。您可以使用此方法-它允许将字符串拆分为任意大小的块:
public static IEnumerable<string> SplitInChunks(string s, int size = 2)
{
return s.Select((c, i) => new {c, id = i / size})
.GroupBy(x => x.id, x => x.c)
.Select(g => new string(g.ToArray()));
}
公共静态IEnumerable SplitInChunks(字符串s,int size=2)
{
返回s.Select((c,i)=>new{c,id=i/size})
.GroupBy(x=>x.id,x=>x.c)
.Select(g=>newstring(g.ToArray());
}
但如果您绑定到regex,请使用以下代码:
public static IEnumerable<string> SplitInChunksWithRegex(string s, int size = 2)
{
var regex = new Regex($".{{1,{size}}}");
return regex.Matches(s).Cast<Match>().Select(m => m.Value);
}
公共静态IEnumerable SplitInChunksWithRegex(字符串s,int size=2)
{
var regex=newregex($”{{1,{size}}”);
返回regex.Matches(s.Cast().Select(m=>m.Value);
}
我不会为此使用正则表达式。我只需迭代字符并将它们复制到数组中。正则表达式可以匹配两个字符组,但如何匹配其余字符?@“\w{1,2}”
将提供您所需的内容。
public static IEnumerable<string> SplitInChunksWithRegex(string s, int size = 2)
{
var regex = new Regex($".{{1,{size}}}");
return regex.Matches(s).Cast<Match>().Select(m => m.Value);
}