これらの文字列がある場合:
"abc"
=false
"123"
=true
"ab2"
=false
IsNumeric()
文字列が有効な数値であるかどうかを識別できるコマンドなどはありますか?
int n;
bool isNumeric = int.TryParse("123", out n);
C# 7 以降の更新:
var isNumeric = int.TryParse("123", out int n);
または、番号が必要ない場合は、 out パラメータを破棄できます
var isNumeric = int.TryParse("123", out _);
varはそれぞれの型に置き換えることができます!
input
がすべて数値の場合、これは true を返します。よりも優れているかどうかはわかりませんがTryParse
、動作します。
Regex.IsMatch(input, @"^\d+$")
文字に 1 つ以上の数字が混在しているかどうかだけを知りたい場合は、^
+
andを省略し$
ます。
Regex.IsMatch(input, @"\d")
編集: 実際には、非常に長い文字列が TryParse をオーバーフローする可能性があるため、TryParse よりも優れていると思います。
私はこの機能を数回使用しました:
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
(ソース: 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()
したがって、代替手段を避ける必要があります。
10 進数を受け入れたい場合は、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;
}
}
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 数値型 (つまり、標準ライブラリで定義されていないもの) には適合しません。
私はこれが古いスレッドであることを知っていますが、実際にそれを行った回答はありませんでした.非効率的であるか、簡単に再利用できるようにカプセル化されていません. また、文字列が空または 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 に含まれるには大きすぎる文字列を変換できないことによって制限されますが、これは限られた要件であり、これよりも大きな数値を扱う場合は、おそらく追加の特殊な数値処理が必要になると思いますとにかく機能します。
TryParse を使用して、文字列を整数に解析できるかどうかを判断できます。
int i;
bool bNum = int.TryParse(str, out i);
ブール値は、それが機能したかどうかを示します。
文字列が数値かどうかを知りたい場合は、いつでも解析してみてください。
var numberString = "123";
int number;
int.TryParse(numberString , out number);
TryParse
を返すことに注意してくださいbool
。これを使用して、解析が成功したかどうかを確認できます。
bool Double.TryParse(string s, out double result)
c# 7 では、out 変数をインライン化できます。
if(int.TryParse(str, out int v))
{
}
お役に立てれば
string myString = "abc";
double num;
bool isNumber = double.TryParse(myString , out num);
if isNumber
{
//string is number
}
else
{
//string is not a number
}
これがC#メソッドです。 Int.TryParse メソッド (文字列、Int32)