[英]C# RegEx Pattern to Split a String into 2 Character Substring
我試圖找出一個正則表達式,用於將字符串分成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根據您的要求,那么, Take
字符串的索引(2,4,6,8,...)在得到字符的塊,並Join
他們string
。
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));
}
用輸入,我有輸出
Idno1 -->
Id
no
1
Id n o 2 -->
Id
n
o
2
在這種情況下,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()));
}
但是,如果您必須使用正則表達式,請使用以下代碼:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.