【发布时间】:2017-01-04 22:05:59
【问题描述】:
我有这个方法,它接受一个字符串,只从中获取数字并修剪空格,但它不起作用:
public static string ToNumericOnlyFAX(this string input)
{
if (input == "OFF6239750")
{
input = Regex.Replace(input, "[^0-9']", " "); - becomes " 6239750"
input.TrimStart().Trim().TrimEnd(); - after any of these its still the above, I want it to be "6239750"
if (input.Length <= 10 && input == "6239750") - if the above works then I can padleft
{
input.PadLeft(10, '0');
}
}
return input;
}
如果空格在数字之间,如 603 123 4321 ???
【问题讨论】:
-
字符串是不可变的 -
Trim()调用等会返回一个新字符串 - 所以你可以使用类似input = input.Trim();和input = input.PadLeft(10, '0');等的东西 -
您可以简单地将您的正则表达式更改为 ...
Regex.Replace(input, "[^0-9']", "");...我的意思是您不需要替换为空格。 -
@stuartd 如何修剪字符串之间的空格??
-
这个问题是怎么重复的?修剪空格和替换字符串中的两个单词之间存在巨大差异。在你们做出愚蠢的决定之前,请阅读问题。
-
确实,修剪空格和替换两个单词是有区别的。但是这些都不是您遇到的问题,您和副本中的人都遇到的问题是您不知道字符串是不可变的。现在你可以了。