将标准化电话号码转换为用户友好版本

发布于 2024-07-11 06:38:21 字数 372 浏览 6 评论 0原文

在我的 C# 应用程序中,我使用正则表达式来验证美国电话号码的基本格式,以确保用户不只是输入虚假数据。 然后,我删除除数字之外的所有内容,因此:

(123) 456-7890 x1234

变为

12345678901234

数据库中为 。 然而,在我的应用程序的各个部分,我想将这个标准化的电话号码转换回

(123) 456-7890 x1234

做这样的事情最好的方法是什么? (顺便说一下,不必担心国际电话号码格式的问题。)

In my C# application, I use a regular expression to validate the basic format of a US phone number to make sure that the user isn't just entering bogus data. Then, I strip out everything except numbers, so this:

(123) 456-7890 x1234

becomes

12345678901234

in the database. In various parts of my application, however, I would like to convert this normalized phone number back to

(123) 456-7890 x1234

What's the best way to do such a thing? (Don't worry about accounting for international phone number formats, by the way.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

幸福不弃 2024-07-18 06:38:22

我只需使用自定义格式字符串将数字转换回字符串:

class Program
{
    static void Main(string[] args)
    {
        long phoneNumber = 12345678901234;
        string phoneNumberString = String.Format("{0:(000) 000-0000 x0000}", phoneNumber);
        Console.WriteLine(phoneNumberString);
    }
}

当然,您可以将其分解为一个函数,该函数将电话号码作为 long ,然后返回字符串(格式加载或存储为方法中的常数,或适合您情况的常数)。

哦,如果你把它放在字符串中而不是长整型,你可以轻松地将字符串转换为长整型,然后将其传递给格式函数。 当然,如果您重复执行此操作,则需要考虑性能(因为您正在迭代字符串以创建 long,然后将其转换回字符串,而您可以只使用子字符串)。

I would just use a custom format string to transform the number back into the string:

class Program
{
    static void Main(string[] args)
    {
        long phoneNumber = 12345678901234;
        string phoneNumberString = String.Format("{0:(000) 000-0000 x0000}", phoneNumber);
        Console.WriteLine(phoneNumberString);
    }
}

Of course, you would factor it out into a function which would take the phone number as a long and then return the string (with the format loaded or stored as a constant in the method, or something appropriate for your situation).

Oh, and if you have it in a string and not a long, you can easily convert the string to a long, and then pass it to the format function. Of course, there are performance considerations here if you are doing it repeatedly (since you are iterating the string to create the long, and then converting it back to a string, when you could just use substring).

眼眸印温柔 2024-07-18 06:38:22

如果您仅支持美国号码,则只需将数字格式化即可在任意位置显示括号和 x。

我更喜欢存储整个字符串,我会使用正则表达式对其进行解析以验证它,然后将其存储在规范化字符串中。

为了让它接受任何国家/地区,我会这样做:

我将 IDD 代码添加到所有电话号码,然后对来自该国家/地区的用户隐藏它。

所以: (123) 456-7890 x1234 将存储为 +1 (123) 456-7890 x1234

(perl 兼容)正则表达式将类似于(完全未经测试且不起作用):

(+\d+)?\ s+(((\d{,3}))(?\s+([-.0-9]{6,})\s+((x|ext\w*)\d{,4})

  • 这是一个前面有多个可选的数字 +
  • 后跟一个或多个空格
  • 然后是括号之间最多 3 个数字的可选组
  • 然后是一个或多个空格
  • 然后是一组 6 个或更多数字、短划线或点
  • 然后是一个或多个空格
  • 然后是可选的 x或以 ext 开头的单词(分机、扩展名...)和一组最多 4 位数字

我将拥有一个用户数据库,包括国家和地区代码,然后自动填写这些内容,以防丢失,国家会有电话号码的默认数字分组约定(美国为 3,4),

  • 因此,如果您位于美国的 123 区,并输入 456.7890,它将被解析为 +1 (123) 4567890,并且您会这样做。 看到它为 456-7890,
  • 仅当您在卡塔尔并输入号码 4444555 extenshn 33 时,才会

它存储为 +974 4444555 x33,您会看到它为 4444555 x33国际代码不会向同一国家/地区的用户显示,并且对于相同国家和区号的用户,不会显示区号。 鼠标悬停时将显示完整的数字(HTML 标签?)

If you only support US numbers, you could simply format the digits to show parenthesis and x wherever you want.

I would prefer to store the whole string, I would parse it using a regex to validate it, then store it in a normalized string.

To make it accept any country, I would do this:

I would add the IDD code to all phone numbers, and then hide it from users from that country.

so: (123) 456-7890 x1234 would be stored as +1 (123) 456-7890 x1234

The (perl-compatible) regex would be something like (completely untested and wouldn't work) :

(+\d+)?\s+(((\d{,3}))(?\s+([-.0-9]{6,})\s+((x|ext\w*)\d{,4})

  • This is an optional number of digits preceded by +
  • Followed by one or more spaces
  • Then an optional group of up to 3 digits between parenthesis
  • Then one or more spaces
  • Then a group of 6 or more digits, dashes or dots
  • Then one or more spaces
  • Then an optional x or a word that begins with ext (ext, extension ...) and a group of up to 4 digits

I would have a database of users including country and area code, then fill those in automatically in case they're missing, the country would have it's default digit grouping convention for phone numbers (3,4 for the us).

  • So if you're in area 123 in the us, and enter 456.7890, it would be parsed as +1 (123) 4567890, and you would only see it as 456-7890
  • if you're in Qatar and enter the number 4444555 extenshn 33, it is stored as +974 4444555 x33, you would see it as 4444555 x33

The international code will not be displayed for users in the same country, and the area code will not be displayed for users in the same country and area code. The full number would be displayed onmouseover (HTML label?)

剪不断理还乱 2024-07-18 06:38:22

您必须为数据库分解它吗? 如果没有,就不要。 如果必须,那么您可以将不同部分存储在不同字段中(区号、前缀、订阅者编号、分机号)。

或者,提取数字,然后开始解析。 如果只有 10 位数字,那么您就知道没有扩展名。 所有超过 10 的数字,将它们粘贴在字符串中的“x”或其他内容之后。

我在 C++ 应用程序中做了类似的事情,我将存储的不同联系机制编写为单个字符串,但相反,我做了与您正在做的相反的事情。 我从对话框中取出了字段,并构建了格式化数字以存储为字符串。

Do you HAVE to break it down for the DB? If not, don't. If you MUST, then you can either store the different parts in different fields, (Areacode, Prefix, SubscriberNum, Extenion).

Or, extract the number, and begin parsing. If it's only 10 digits, then you know there is no extension. All digits past 10, stick them in the string after an 'x' or something.

I did something similar to this in a C++ app I wrote the stored different contact mechanisms as a single string, but instead, I did the reverse of what you are doing. I took the fields off a dialog, and built the formatted number to store as a string.

月隐月明月朦胧 2024-07-18 06:38:22

这是一个可能有帮助的扩展方法:

public static string InsertStringAtPositions(this string str, string insertStr, IEnumerable<int> positions)
{
    if (str != null && insertStr != null && positions != null)
    {
        string newString = string.Empty;
        int previousPos = 0;
        foreach (var pos in positions)
        {
            if (pos < str.Length)
            {
                newString += str.Substring(previousPos, pos - previousPos) + insertStr;
                previousPos = pos;
            }
        }
        if (positions.Last() < str.Length)
        {
            return newString + str.Substring(positions.Last(), str.Length - positions.Last());
        }
        return newString;
    }
    return str;
}

用法:

// Will convert "0399998888" to "03 9999 8888"
number.InsertStringAtPositions(" ", new[] {2, 6});

Here's an extension method that might help:

public static string InsertStringAtPositions(this string str, string insertStr, IEnumerable<int> positions)
{
    if (str != null && insertStr != null && positions != null)
    {
        string newString = string.Empty;
        int previousPos = 0;
        foreach (var pos in positions)
        {
            if (pos < str.Length)
            {
                newString += str.Substring(previousPos, pos - previousPos) + insertStr;
                previousPos = pos;
            }
        }
        if (positions.Last() < str.Length)
        {
            return newString + str.Substring(positions.Last(), str.Length - positions.Last());
        }
        return newString;
    }
    return str;
}

Usage:

// Will convert "0399998888" to "03 9999 8888"
number.InsertStringAtPositions(" ", new[] {2, 6});
杯别 2024-07-18 06:38:21
String.Format("{0:(###) ###-#### x ###}", double.Parse("1234567890123"))

将导致 (123) 456-7890 x 123

String.Format("{0:(###) ###-#### x ###}", double.Parse("1234567890123"))

Will result in (123) 456-7890 x 123

守不住的情 2024-07-18 06:38:21

使用正则表达式,您可以将:替换

(\d{3})(\d{3})(\d{4})(\d{4})

为:(

(\1) \2-\3 x\4

虽然我不熟悉美国电话号码,所以也许还有更多内容。)

Using a regex you can replace:

(\d{3})(\d{3})(\d{4})(\d{4})

with:

(\1) \2-\3 x\4

(Though I'm not familiar with US phone numbers so maybe there's more to it.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文