使用自定义格式字符串将字符串解析为 int/long

R D*_*R D 6 .net c# int parsing custom-formatting

在 C#.Net 中,以下是如何使用自定义格式字符串将数字格式化为字符串的简单示例:(示例取自:http://www.csharp-examples.net/string-format-int/

String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456"
String.Format("{0:##-####-####}", 8958712551);       // "89-5871-2551"
Run Code Online (Sandbox Code Playgroud)

有没有办法将此格式化字符串转换回 long/integer ?有什么办法可以做到这一点:

long PhoneNumber = Int32.Parse("89-5871-2551", "{0:##-####-####}");
Run Code Online (Sandbox Code Playgroud)

我看到 DateTime 有一个方法 ParseExact 可以很好地完成这项工作。但我没有看到 int/long/decimal/double 的任何这样的东西。

Cha*_*ell 5

您可以用正则表达式输出所有非数字,剩下的就是一串可以解析的数字。

var myPhoneNumber = "89-5871-2551";
var strippedPhoneNumber = Regex.Replace(myPhoneNumber, @"[^\d]", "");
int intRepresentation;

if (Int32.TryParse(strippedPhoneNumber, out intRepresentation))
{
    // It was assigned, intRepresentation = 8958712551
    // now you can use intRepresentation.

} else {
    // It was not assigned, intRepresentation is still null.
}
Run Code Online (Sandbox Code Playgroud)


eou*_*3hf 0

只需使用正则表达式删除所有非数字字符,然后解析该字符串即可。