【问题标题】:How to strip away letters from string?如何从字符串中去除字母?
【发布时间】:2010-06-17 14:48:23
【问题描述】:

我想去掉字符串中所有非数字的字母。最好是用正则表达式或其他东西制作的解决方案。在 C# 中。 怎么做?

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    使用正则表达式:

    str = Regex.Replace(str, @"\D+", "");
    

    \D\d 的补码 - 匹配所有不是数字的内容。 + 将匹配其中的一个或多个(通常比一个一个好一点)。

    使用 Linq(在 .Net 4.0 上):

    str = String.Concat(str.Where(Char.IsDigit));
    

    【讨论】:

      【解决方案2】:
      string str = "ab123123abc"
      str = Regex.Replace(str, @"[\w]", ""); 
      

      引用自 http://msdn.microsoft.com/en-us/library/844skk0h.aspx

      【讨论】:

      • [\w] 是多余的,你不需要字符类。 \w 完全一样。但是,\w 包含字母和数字(以及下划线),因此最终会出现特殊字符和空格。
      【解决方案3】:

      我更喜欢使用 not ^ like ^\d or ^[0-9]

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

      【讨论】:

      • 嗯,这基本上是一样的,但可能更广为人知。不需要try/catch 块,唯一可能的例外是subjectStringnull,您最好检查一下。对于此模式,您不会得到 ArgumentException - 这是正确的 :) 但是,应该是“[^\d][^0-9]
      【解决方案4】:
      string result = System.Text.RegularExpressions.Regex.Replace("text to look for stuff", "pattern", "what to replace it with")
      

      【讨论】:

      • 嗯,好吗?这有什么用?正则表达式如何工作?你是如何神秘地使用这种“模式”的东西的?这又是如何回答这个问题的呢?
      • 我的假设只是他不知道如何在 c# 中调用正则表达式替换,而不是想要确切的代码来执行它。在阅读了其他答案后,我意识到我的答案是不想要的,但感谢您指出我错了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多