只保留数值从字符串? [英] Keep only numeric value from a string?

查看:103
本文介绍了只保留数值从字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些字符串这样

string phoneNumber = "(914) 395-1430";



我想带出的parethenses和仪表板,在其他的词,仅仅保留数值。

I would like to strip out the parethenses and the dash, in other word just keep the numeric values.

所以输出可能看起来像这样

So the output could look like this

9143951430

我如何获得所需的输出?

How do I get the desired output ?

推荐答案

您请执行下列操作之一:

You do any of the following:


  • 使用正则表达式。您可以使用正则表达式为

  • Use regular expressions. You can use a regular expression with either


  • 一个否定的字符类,定义是你不想要的东西(人物不是小数位数其他那些字符):

  • A negative character class that defines the characters that are what you don't want (those characters other than decimal digits):

private static readonly Regex rxNonDigits = new Regex( @"[^\d]+");

在这种情况下,你可以做采取这些方法的执行:

In which case, you can do take either of these approaches:

// simply replace the offending substrings with an empty string
private string CleanStringOfNonDigits_V1( string s )
{
  if ( string.IsNullOrEmpty(s) ) return s ;
  string cleaned = rxNonDigits.Replace(s, "") ;
  return cleaned ;
}

// split the string into an array of good substrings
// using the bad substrings as the delimiter.
// Then aggregate that into a StringBuilder to get the result.
private string CleanStringOfNonDigits_V2( string s )
{
  if (string.IsNullOrEmpty(s)) return s;
  string cleaned = rxNonDigits
                   .Split(s)
                   .Aggregate(new StringBuilder(), (sb,ss) => sb.Append(ss) )
                   .ToString()
                   ;
  return cleaned ;
}


  • 一个积极的字符集,定义你想要什么(十进制数字):

  • a positive character set that defines what you do want (decimal digits):

    private static Regex rxDigits = new Regex( @"[\d]+") ;
    

    在这种情况下,你可以做这样的事情:

    In which case you can do something like this:

    private string CleanStringOfNonDigits_V3( string s )
    {
      if ( string.IsNullOrEmpty(s) ) return s ;
      StringBuilder sb = new StringBuilder() ;
      for ( Match m = rxDigits.Match(s) ; m.Success ; m = m.NextMatch() )
      {
        sb.Append(m.Value) ;
      }
      string cleaned = sb.ToString() ;
      return cleaned ;
    }
    


  • 您再不需要使用正则表达式,无论是。

    You're not required to use a regular expression, either.


    • 您可以直接使用LINQ,因为一个字符串是的IEnumerable<焦炭>

    private string CleanStringOfNonDigits_V4( string s )
    {
      if ( string.IsNullOrEmpty(s) ) return s;
      string cleaned = new string( s.Where( char.IsDigit ).ToArray() ) ;
      return cleaned;
    }
    


  • 如果你只对付西方的字母,唯一的十进制你会看到数字是ASCII,跳过 char.IsDigit 将有可能给你买一个小的性能:

  • If you're only dealing with western alphabets where the only decimal digits you'll see are ASCII, skipping char.IsDigit will likely buy you a little performance:

    private string CleanStringOfNonDigits_V5( string s )
    {
      if (string.IsNullOrEmpty(s)) return s;
      string cleaned = new string(s.Where( c => c-'0' < 10 ).ToArray() ) ;
      return cleaned;
    }
    


  • 最后,你可以简单地遍历字符串,夹紧你不想要的数字,像这样的:

    Finally, you can simply iterate over the string, chucking the digits you don't want, like this:

    private string CleanStringOfNonDigits_V6( string s )
    {
      if (string.IsNullOrEmpty(s)) return s;
      StringBuilder sb = new StringBuilder(s.Length) ;
      for (int i = 0; i < s.Length; ++i)
      {
        char c = s[i];
        if ( c < '0' ) continue ;
        if ( c > '9' ) continue ;
        sb.Append(s[i]);
      }
      string cleaned = sb.ToString();
      return cleaned;
    }
    

    或者这样的:

    private string CleanStringOfNonDigits_V7(string s)
    {
      if (string.IsNullOrEmpty(s)) return s;
      StringBuilder sb = new StringBuilder(s);
      int j = 0 ;
      int i = 0 ;
      while ( i < sb.Length )
      {
        bool isDigit = char.IsDigit( sb[i] ) ;
        if ( isDigit )
        {
          sb[j++] = sb[i++];
        }
        else
        {
          ++i ;
        }
      }
      sb.Length = j;
      string cleaned = sb.ToString();
      return cleaned;
    }
    


    从一个角度看清晰度和代码清洁,版本1是你想要的。它是很难被击败一个衬垫。

    From a standpoint of clarity and cleanness of code, the version 1 is what you want. It's hard to beat a one liner.

    如果性能问题,我怀疑是版本7,最后的版本,是赢家。它会创建一个临时&MDASH;一个的StringBuilder()并执行就地StringBuilder中的就地缓冲区内的改造。

    If performance matters, my suspicion is that the version 7, the last version, is the winner. It creates one temporary — a StringBuilder() and does the transformation in-place within the StringBuilder's in-place buffer.

    其他的选项所有做更多的工作。

    The other options all do more work.

    这篇关于只保留数值从字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆