我正在尝试找出一个正则表达式来将字符串拆分为 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 可以使代码变得简单。 Fiddle版本有效
想法:我有一个 chunkSize
= 2 作为您的要求,然后,获取
索引处的字符串 (2,4,6,8,... ) 获取字符 block 并将它们加入
到字符串
。
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
关于C# RegEx 模式将字符串拆分为 2 个字符的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51770742/