在文本框中的数字之间插入空格

时间:2014-02-10 23:48:00

标签: c# asp.net regex

您好,感谢您的阅读。

我有这个TextBox,用户可以输入他/她的电话号码。

<asp:TextBox runat="server" ID="txtPhone" CssClass="TicketField FieldWidthH txtboxStyle" />

如果用户键入12345678,我希望自动“显示”12 34 56 78,这样每2个数字后面就有一个空格。

这是我的C#代码:

if (IsPostBack) {
    if (!string.IsNullOrEmpty(txtPhone.Text)) {
        // Check if the value contains any non-numeric values and strip them out
        string cleanedUpTextBoxValue = Regex.Replace(txtPhone.Text, @"^\d{6}$", "");

         // Parse your number as an integer from your TextBox (after cleaning it up)
         Int64 yourIntegerTextBoxValue = Int64.Parse(cleanedUpTextBoxValue);

         // Format your number as a string
         string formattedResult = yourIntegerTextBoxValue.ToString("## ## ## ##");

         // Output the result into your TextBox
         txtPhone.Text = formattedResult;
    }
}

我也试过string cleanedUpTextBoxValue = Regex.Replace(txtPhone.Text, "[^\d]", "");

但是我输入文本框我仍然只显示数字12345678。

我做错了什么?

感谢您的时间

2 个答案:

答案 0 :(得分:2)

如果可能的话,我通常建议使用JavaScript,但是如果你想要一个C#解决方案,你可以用它去除非数字字符:

string text = Regex.Replace(txtPhone.Text, @"\D", "");

然后在每对数字周围插入空格:

text = Regex.Replace(text, @"\d\d(?!$)", "$0 ");
txtPhone.Text = text;

如果在JavaScript中实现,它看起来有点像这样:

text = text.replace(/\D/g, '').replace(/(\d\d)(?!$)/g, '$1 ')

答案 1 :(得分:1)

使用字符串的Insert方法。

string phone = txtPhone.Text; // or your cleaned-up string
phone = phone.Insert(2, " ");
txtPhone.Text = phone;

您可以在其中放置一个循环,以根据需要在每个其他数字之间获取空格。从最后开始,在字符串的长度上循环可能是最简单的。检查字符串的长度以确定您的起始位置(即最后一个字符或最后一个字符)。如果用户输入奇数位数会怎样?