如何将string
转换为给定的模式。考虑模式可以是任何东西。
示例:
1234567890
XXXX-XXXX-XX
,则输出为-1234-5678-90
XXX-XXX-XXX-X
,则输出为-123-456-789-0
XXX=XXX=XXX=X
,则输出为-123=456=789=0
XX-XXX-X-XXXX
,则输出为-12-345-6-7890
注意:输入字符串的长度可能会有所不同。
我尝试过
Console.WriteLine(Regex.Replace("1235645847", ".{1,4}", "$&-").TrimEnd('-'));
但这不是不是动态,它仅适用于第一个模式。
有可能实现这一目标吗?任何帮助表示赞赏。
答案 0 :(得分:3)
正如已经说过的,这与正则表达式没有什么共同点。好吧,除了模式,但是您在不同的上下文中使用它。您只需要使用某种模式来格式化一些字符串即可。
您可以使用以下功能作为示例:
public string ConvertToFormat(string strToFormat, string pattern)
{
if (pattern.Count(c => c == 'X') != strToFormat.Length)
throw new ArgumentException("Number of placeholders in pattern is different from number of characters in the input string!");
StringBuilder sb = new StringBuilder();
int j = 0;
for(int i = 0; i < pattern.Length; i++)
if (pattern[i] == 'X')
{
sb.Append(strToFormat[j]);
j++;
}
else
sb.Append(pattern[i]);
return sb.ToString();
}
并像这样使用:
string result = ConvertToFormat("1234567890", "XXXX-XXXX-XX");
result = ConvertToFormat("1234567890", "XXX-XXX-XXX-X");
result = ConvertToFormat("1234567890", "XXX=XXX=XXX=X");
更新
带有正则表达式的动态解决方案:
public string RegexConvertToFormat(string strToFormat, int blockSize, char separator)
{
return Regex.Replace("1235645847", ".{" + blockSize + "}" , "$&" + separator).TrimEnd(separator);
}
用法:
string s = RegexConvertToFormat("1234567890", 4, '-');
s = RegexConvertToFormat("1234567890", 3, '-');
s = RegexConvertToFormat("1234567890", 3, '=');
答案 1 :(得分:3)
string input="123456789";
var pattern="XXX-XXX=XXX";
var reg=new Regex(new string('N',input.Length).Replace("N","(\\w)"));//1.
var regX=new Regex("X");
for (int i = 1; i <= input.Length; i++)
{
pattern=regX.Replace(pattern,"$"+i.ToString(),1);//2.
}
Console.WriteLine( reg.Replace(input,pattern));
1.将输入123456789
替换为(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)
个多组
XXX-XXX=XXX
替换为组替换$1$2$3-$4$5$6=$7$8$9
答案 2 :(得分:1)
一个简单的 Linq 可以做到:
public static string ApplyPattern(string value, string mask) {
if (null == value)
throw new ArgumentNullException("value");
else if (null == mask)
throw new ArgumentNullException("mask");
else if (mask.Count(c => c == 'X') != value.Length)
throw new ArgumentException("Inconsistent mask", "mask");
int index = 0;
// index++ - side effect - which is, however, safe in the context
return string.Concat(mask
.Select(c => c == 'X' ? value[index++] : c));
}
演示:
string[] testMasks = new string[] {
"XXXX-XXXX-XX",
"XXX-XXX-XXX-X",
"XXX=XXX=XXX=X",
"XX-XXX-X-XXXX",
"+XX-=XXX-X--XXXX",
"+(XX)=XXX-X--XXXX?",
};
string report = string.Join(Environment.NewLine, testMasks
.Select(mask => $"{mask,20} -> {ApplyPattern("1234567890", mask)}"));
Console.Write(report);
结果:
XXXX-XXXX-XX -> 1234-5678-90
XXX-XXX-XXX-X -> 123-456-789-0
XXX=XXX=XXX=X -> 123=456=789=0
XX-XXX-X-XXXX -> 12-345-6-7890
+XX-=XXX-X--XXXX -> +12-=345-6--7890
+(XX)=XXX-X--XXXX? -> +(12)=345-6--7890?