【问题标题】:Trim Function not getting rid of white spaces in string [duplicate]修剪功能没有摆脱字符串中的空格[重复]
【发布时间】: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 如何修剪字符串之间的空格??
  • 这个问题是怎么重复的?修剪空格和替换字符串中的两个单词之间存在巨大差异。在你们做出愚蠢的决定之前,请阅读问题。
  • 确实,修剪空格和替换两个单词是有区别的。但是这些都不是您遇到的问题,您和副本中的人都遇到的问题是您不知道字符串是不可变的。现在你可以了。

标签: c# regex trim


【解决方案1】:

另外,为什么需要用空格替换? 例如,您可以将其更改为:

input = Regex.Replace(input, "[^0-9']", ""); - becomes "6239750".

请注意:此正则表达式将删除所有个字符,包括空格。

【讨论】:

  • 感谢好友,此解决方案甚至可以删除字符串之间的空格,而 trim、trimstart 和 trim end 无法完成。
  • :) 很高兴它起作用了。我已经更新了原始帖子以明确这一点。
【解决方案2】:

尝试使用:

string subjectString = "OFF6239750";
string resultString = null;
try {
    resultString = Regex.Match(subjectString, @"\d+").Value;
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}

【讨论】:

    猜你喜欢
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    相关资源
    最近更新 更多