developer tip

문자열이 숫자인지 식별

copycodes 2020. 9. 30. 11:04
반응형

문자열이 숫자인지 식별


이 문자열이있는 경우 :

  1. "abc" = false

  2. "123" = true

  3. "ab2" = false

IsNumeric()문자열이 유효한 숫자인지 식별 ​​할 수 있는 명령 이 있습니까?


int n;
bool isNumeric = int.TryParse("123", out n);

C # 7부터 업데이트 :

var isNumeric = int.TryParse("123", out int n);

var에 들 각각의 유형에 의해 대체 될 수 있습니다!


input모든 숫자 이면 true를 반환합니다 . 이보다 나은지 TryParse모르겠지만 작동합니다.

Regex.IsMatch(input, @"^\d+$")

문자와 혼합 된 하나 이상의 숫자가 있는지 알고 싶다면 ^ +$.

Regex.IsMatch(input, @"\d")

편집 : 실제로 매우 긴 문자열이 잠재적으로 TryParse를 오버플로 할 수 있기 때문에 TryParse보다 낫다고 생각합니다.


다음을 사용할 수도 있습니다.

stringTest.All(char.IsDigit);

그것은 반환 true모든 자리 숫자 (하지 않는 float) 및 false입력 문자열은 숫자의 어떤 종류 인 경우.

참고 : stringTest숫자 테스트를 통과하므로 빈 문자열이 아니어야합니다.


이 기능을 여러 번 사용했습니다.

public static bool IsNumeric(object Expression)
{
    double retNum;

    bool isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
    return isNum;
}

그러나 사용할 수도 있습니다.

bool b1 = Microsoft.VisualBasic.Information.IsNumeric("1"); //true
bool b2 = Microsoft.VisualBasic.Information.IsNumeric("1aa"); // false

IsNumeric 옵션 벤치마킹 에서

대체 텍스트
(출처 : aspalliance.com )

대체 텍스트
(출처 : aspalliance.com )


이것은 아마도 C #에서 가장 좋은 옵션 일 것입니다.

문자열에 정수 (정수)가 포함되어 있는지 알고 싶다면 :

string someString;
// ...
int myInt;
bool isNumerical = int.TryParse(someString, out myInt);

TryParse 메서드는 문자열을 숫자 (정수)로 변환하려고 시도하고 성공하면 true를 반환하고 해당 숫자를 myInt에 배치합니다. 할 수 없으면 false를 반환합니다.

int.Parse(someString)다른 응답에 표시된 대안을 사용하는 솔루션 은 작동하지만 예외를 던지는 것은 매우 비싸기 때문에 훨씬 느립니다. TryParse(...)버전 2의 C # 언어에 추가되었으며 그때까지는 선택의 여지가 없었습니다. 이제해야합니다. 따라서 Parse()대안을 피해야합니다 .

십진수를 허용하려면 decimal 클래스에도 .TryParse(...)메서드가 있습니다. 위의 논의에서 int를 decimal로 바꾸면 동일한 원칙이 적용됩니다.


항상 많은 데이터 유형에 대해 내장 된 TryParse 메서드를 사용하여 문제의 문자열이 통과되는지 확인할 수 있습니다.

예.

decimal myDec;
var Result = decimal.TryParse("123", out myDec);

결과 = True

decimal myDec;
var Result = decimal.TryParse("abc", out myDec);

결과 = False


int.Parse 또는 double.Parse를 사용하지 않으려는 경우 다음과 같이 직접 굴릴 수 있습니다.

public static class Extensions
{
    public static bool IsNumeric(this string s)
    {
        foreach (char c in s)
        {
            if (!char.IsDigit(c) && c != '.')
            {
                return false;
            }
        }

        return true;
    }
}

나는 이것이 오래된 스레드라는 것을 알고 있지만 비효율적이거나 쉬운 재사용을 위해 캡슐화되지 않은 대답은 실제로 나를 위해 해주지 않았습니다. 또한 문자열이 비어 있거나 null 인 경우 false를 반환하도록하고 싶었습니다. 이 경우 TryParse는 true를 반환합니다 (빈 문자열은 숫자로 구문 분석 할 때 오류를 일으키지 않음). 그래서 여기에 내 문자열 확장 방법이 있습니다.

public static class Extensions
{
    /// <summary>
    /// Returns true if string is numeric and not empty or null or whitespace.
    /// Determines if string is numeric by parsing as Double
    /// </summary>
    /// <param name="str"></param>
    /// <param name="style">Optional style - defaults to NumberStyles.Number (leading and trailing whitespace, leading and trailing sign, decimal point and thousands separator) </param>
    /// <param name="culture">Optional CultureInfo - defaults to InvariantCulture</param>
    /// <returns></returns>
    public static bool IsNumeric(this string str, NumberStyles style = NumberStyles.Number,
        CultureInfo culture = null)
    {
        double num;
        if (culture == null) culture = CultureInfo.InvariantCulture;
        return Double.TryParse(str, style, culture, out num) && !String.IsNullOrWhiteSpace(str);
    }
}

간편한 사용 :

var mystring = "1234.56789";
var test = mystring.IsNumeric();

또는 다른 유형의 숫자를 테스트하려는 경우 '스타일'을 지정할 수 있습니다. 따라서 지수로 숫자를 변환하려면 다음을 사용할 수 있습니다.

var mystring = "5.2453232E6";
var test = mystring.IsNumeric(style: NumberStyles.AllowExponent);

또는 잠재적 인 16 진수 문자열을 테스트하려면 다음을 사용할 수 있습니다.

var mystring = "0xF67AB2";
var test = mystring.IsNumeric(style: NumberStyles.HexNumber)

선택적 'culture'매개 변수는 거의 동일한 방식으로 사용할 수 있습니다.

너무 큰 문자열을 double에 포함 할 수 없다는 점으로 제한되지만 제한적인 요구 사항이며 이보다 큰 숫자로 작업하는 경우 추가 특수 숫자 처리가 필요할 것입니다. 어쨌든 기능.


PHP의 is_numeric 보다 광범위한 숫자를 포착 하려면 다음을 사용할 수 있습니다.

// From PHP documentation for is_numeric
// (http://php.net/manual/en/function.is-numeric.php)

// Finds whether the given variable is numeric.

// Numeric strings consist of optional sign, any number of digits, optional decimal part and optional
// exponential part. Thus +0123.45e6 is a valid numeric value.

// Hexadecimal (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but
// only without sign, decimal and exponential part.
static readonly Regex _isNumericRegex =
    new Regex(  "^(" +
                /*Hex*/ @"0x[0-9a-f]+"  + "|" +
                /*Bin*/ @"0b[01]+"      + "|" + 
                /*Oct*/ @"0[0-7]*"      + "|" +
                /*Dec*/ @"((?!0)|[-+]|(?=0+\.))(\d*\.)?\d+(e\d+)?" + 
                ")$" );
static bool IsNumeric( string value )
{
    return _isNumericRegex.IsMatch( value );
}

단위 테스트 :

static void IsNumericTest()
{
    string[] l_unitTests = new string[] { 
        "123",      /* TRUE */
        "abc",      /* FALSE */
        "12.3",     /* TRUE */
        "+12.3",    /* TRUE */
        "-12.3",    /* TRUE */
        "1.23e2",   /* TRUE */
        "-1e23",    /* TRUE */
        "1.2ef",    /* FALSE */
        "0x0",      /* TRUE */
        "0xfff",    /* TRUE */
        "0xf1f",    /* TRUE */
        "0xf1g",    /* FALSE */
        "0123",     /* TRUE */
        "0999",     /* FALSE (not octal) */
        "+0999",    /* TRUE (forced decimal) */
        "0b0101",   /* TRUE */
        "0b0102"    /* FALSE */
    };

    foreach ( string l_unitTest in l_unitTests )
        Console.WriteLine( l_unitTest + " => " + IsNumeric( l_unitTest ).ToString() );

    Console.ReadKey( true );
}

값이 숫자라고해서 숫자 유형으로 변환 할 수있는 것은 아닙니다. 예를 들어 "999999999999999999999999999999.9999999999"는 완전한 유효한 숫자 값이지만 .NET 숫자 유형 (표준 라이브러리에 정의 된 유형이 아님)에 맞지 않습니다.


TryParse를 사용하여 문자열을 정수로 구문 분석 할 수 있는지 확인할 수 있습니다.

int i;
bool bNum = int.TryParse(str, out i);

부울은 작동 여부를 알려줍니다.


문자열이 숫자인지 확인하고 싶다면 (숫자이면 문자열이라고 가정하고 있습니다.

  • 정규식없이
  • Microsoft의 코드를 가능한 많이 사용

당신은 또한 할 수 있습니다 :

public static bool IsNumber(this string aNumber)
{
     BigInteger temp_big_int;
     var is_number = BigInteger.TryParse(aNumber, out temp_big_int);
     return is_number;
}

이것은 일반적인 문제를 처리합니다.

  • 처음에 빼기 (-) 또는 더하기 (+)
  • 10 진수 문자 포함BigIntegers는 소수점으로 숫자를 구문 분석하지 않습니다. (그래서 : BigInteger.Parse("3.3")예외가 발생 TryParse하고 동일한 경우 false를 반환합니다)
  • 재미없는 숫자 없음
  • 숫자가 일반적인 사용보다 큰 경우를 다룹니다. Double.TryParse

당신은 참조를 추가하고 당신의 클래스 위에 System.Numerics있어야 using System.Numerics;할 것입니다 (글쎄, 두 번째는 보너스입니다 :)


나는이 대답이 다른 모든 대답 사이에서 사라질 것이라고 생각하지만 어쨌든 여기에 있습니다.

나는 방법 대신 사용할 수 있도록 a string있는지 확인하고 싶었 기 때문에 Google을 통해이 질문에 답했습니다 .numericdouble.Parse("123")TryParse()

왜? 구문 분석이 실패했는지 여부를 알기 전에 out변수 를 선언 하고 결과를 확인 해야하는 것이 귀찮기 TryParse()때문입니다. 나는를 사용하려면 ternary operator(가) 있는지 확인하는 string것입니다 numerical후 바로 첫 번째 삼항 표현식에서 구문 분석 또는 두 번째 삼원 식의 디폴트 값을 제공합니다.

이렇게 :

var doubleValue = IsNumeric(numberAsString) ? double.Parse(numberAsString) : 0;

다음보다 훨씬 더 깨끗합니다.

var doubleValue = 0;
if (double.TryParse(numberAsString, out doubleValue)) {
    //whatever you want to do with doubleValue
}

extension methods이 경우를 위해 몇 가지 만들었습니다 .


확장 방법 1

public static bool IsParseableAs<TInput>(this string value) {
    var type = typeof(TInput);

    var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
        new[] { typeof(string), type.MakeByRefType() }, null);
    if (tryParseMethod == null) return false;

    var arguments = new[] { value, Activator.CreateInstance(type) };
    return (bool) tryParseMethod.Invoke(null, arguments);
}

예:

"123".IsParseableAs<double>() ? double.Parse(sNumber) : 0;

IsParseableAs()문자열이 "숫자"인지 확인하는 대신 적절한 유형으로 문자열을 구문 분석하려고하기 때문에 상당히 안전해야합니다. .NET TryParse()과 같은 메서드 가있는 숫자가 아닌 유형에도 사용할 수 있습니다 DateTime.

이 메서드는 리플렉션을 사용하고 결국 TryParse()메서드를 두 번 호출하게 되는데 이는 물론 효율적이지는 않지만 모든 것이 완전히 최적화되어야하는 것은 아니며 때로는 편리함이 더 중요합니다.

이 메서드를 사용 double하면 예외를 포착하지 않고도 숫자 문자열 목록을 기본값이 있는 목록 또는 다른 유형으로 쉽게 구문 분석 할 수 있습니다 .

var sNumbers = new[] {"10", "20", "30"};
var dValues = sNumbers.Select(s => s.IsParseableAs<double>() ? double.Parse(s) : 0);

확장 방법 2

public static TOutput ParseAs<TOutput>(this string value, TOutput defaultValue) {
    var type = typeof(TOutput);

    var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
        new[] { typeof(string), type.MakeByRefType() }, null);
    if (tryParseMethod == null) return defaultValue;

    var arguments = new object[] { value, null };
    return ((bool) tryParseMethod.Invoke(null, arguments)) ? (TOutput) arguments[1] : defaultValue;
}

이 확장 방법을 사용하면 구문 분석 할 수 string있는 등 type가 그 TryParse()방법을 그리고 그것은 또한 당신이 변환이 실패 할 경우 반환 할 기본값을 지정할 수 있습니다.

이것은 변환을 한 번만 수행하므로 위의 확장 메서드와 함께 삼항 연산자를 사용하는 것보다 낫습니다. 그래도 반사를 사용합니다 ...

예 :

"123".ParseAs<int>(10);
"abc".ParseAs<int>(25);
"123,78".ParseAs<double>(10);
"abc".ParseAs<double>(107.4);
"2014-10-28".ParseAs<DateTime>(DateTime.MinValue);
"monday".ParseAs<DateTime>(DateTime.MinValue);

출력 :

123
25
123,78
107,4
28.10.2014 00:00:00
01.01.0001 00:00:00

문자열이 숫자인지 알고 싶다면 항상 구문 분석을 시도 할 수 있습니다.

var numberString = "123";
int number;

int.TryParse(numberString , out number);

참고 TryParse리턴한다 bool파싱가 성공했을 경우 사용할 수있는, 확인.


Double.TryParse

bool Double.TryParse(string s, out double result)

Kunal Noel 답변 업데이트

stringTest.All(char.IsDigit);
// This returns true if all characters of the string are digits.

그러나이 경우 빈 문자열이 해당 테스트를 통과하므로 다음을 수행 할 수 있습니다.

if (!string.IsNullOrEmpty(stringTest) && stringTest.All(char.IsDigit)){
   // Do your logic here
}

C # 7에서는 out 변수를 인라인 할 수 있습니다.

if(int.TryParse(str, out int v))
{
}

이러한 확장 방법을 사용하여 문자열이 숫자 인지와 문자열 에 0-9 자리 포함되어 있는지 확인을 명확하게 구분 합니다.

public static class ExtensionMethods
{
    /// <summary>
    /// Returns true if string could represent a valid number, including decimals and local culture symbols
    /// </summary>
    public static bool IsNumeric(this string s)
    {
        decimal d;
        return decimal.TryParse(s, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.CurrentCulture, out d);
    }

    /// <summary>
    /// Returns true only if string is wholy comprised of numerical digits
    /// </summary>
    public static bool IsNumbersOnly(this string s)
    {
        if (s == null || s == string.Empty)
            return false;

        foreach (char c in s)
        {
            if (c < '0' || c > '9') // Avoid using .IsDigit or .IsNumeric as they will return true for other characters
                return false;
        }

        return true;
    }
}

public static bool IsNumeric(this string input)
{
    int n;
    if (!string.IsNullOrEmpty(input)) //.Replace('.',null).Replace(',',null)
    {
        foreach (var i in input)
        {
            if (!int.TryParse(i.ToString(), out n))
            {
                return false;
            }

        }
        return true;
    }
    return false;
}

.net 내장 함수가있는 가장 유연한 솔루션 인 char.IsDigit. 무제한 긴 숫자로 작동합니다. 각 문자가 숫자 인 경우에만 true를 반환합니다. 나는 문제없이 여러 번 사용했으며 내가 찾은 훨씬 쉽게 깨끗한 솔루션을 사용했습니다. 예제 메서드를 만들었습니다. 사용할 준비가되었습니다. 또한 null 및 빈 입력에 대한 유효성 검사를 추가했습니다. 그래서 그 방법은 이제 완전히 방탄입니다

public static bool IsNumeric(string strNumber)
    {
        if (string.IsNullOrEmpty(strNumber))
        {
            return false;
        }
        else
        {
            int numberOfChar = strNumber.Count();
            if (numberOfChar > 0)
            {
                bool r = strNumber.All(char.IsDigit);
                return r;
            }
            else
            {
                return false;
            }
        }
    }

도움이 되었기를 바랍니다

string myString = "abc";
double num;
bool isNumber = double.TryParse(myString , out num);

if isNumber 
{
//string is number
}
else
{
//string is not a number
}

프로젝트에서 Visual Basic에 대한 참조를 가져 와서 아래와 같이 Information.IsNumeric 메서드를 사용하면 위의 답변과 달리 정수뿐만 아니라 부동 소수점도 캡처 할 수 있습니다.

    // Using Microsoft.VisualBasic;

    var txt = "ABCDEFG";

    if (Information.IsNumeric(txt))
        Console.WriteLine ("Numeric");

IsNumeric("12.3"); // true
IsNumeric("1"); // true
IsNumeric("abc"); // false

아래에서 reges를 시도하십시오

new Regex(@"^\d{4}").IsMatch("6")    // false
new Regex(@"^\d{4}").IsMatch("68ab") // false
new Regex(@"^\d{4}").IsMatch("1111abcdefg") ```

모든 답변이 유용합니다. 그러나 숫자 값이 12 자리 이상 (제 경우) 인 솔루션을 검색하는 동안 디버깅하는 동안 다음 솔루션이 유용하다는 것을 알았습니다.

double tempInt = 0;
bool result = double.TryParse("Your_12_Digit_Or_more_StringValue", out tempInt);

결과 변수는 true 또는 false를 제공합니다.


다음은 C # 방법입니다. Int.TryParse 메서드 (String, Int32)


//To my knowledge I did this in a simple way
static void Main(string[] args)
{
    string a, b;
    int f1, f2, x, y;
    Console.WriteLine("Enter two inputs");
    a = Convert.ToString(Console.ReadLine());
    b = Console.ReadLine();
    f1 = find(a);
    f2 = find(b);

    if (f1 == 0 && f2 == 0)
    {
        x = Convert.ToInt32(a);
        y = Convert.ToInt32(b);
        Console.WriteLine("Two inputs r number \n so that addition of these text box is= " + (x + y).ToString());
    }
    else
        Console.WriteLine("One or two inputs r string \n so that concatenation of these text box is = " + (a + b));
    Console.ReadKey();
}

static int find(string s)
{
    string s1 = "";
    int f;
    for (int i = 0; i < s.Length; i++)
       for (int j = 0; j <= 9; j++)
       {
           string c = j.ToString();
           if (c[0] == s[i])
           {
               s1 += c[0];
           }
       }

    if (s == s1)
        f = 0;
    else
        f = 1;

    return f;
}

참고 URL : https://stackoverflow.com/questions/894263/identify-if-a-string-is-a-number

반응형