我看到一個類似的主題(this),但無法達到理想的解決方案。正則表達式替換數字和只有一個連字符C#
我需要什麼:
,關於keypress
事件TextBox
與""
更換非數字和過度連字符的工作的面具。
允許:
什麼是我的難處?
檢查相同表達式中只有一個連字符的輸入。
我使用子串進入解決方案,它只在KeyUP
工作,但我想通過使用表達式和keypress
事件。
我已經嘗試過:
using System.Text.RegularExpressions;
//trying to denie non-digit and hyphen.
//In conjunction with replace I remove everything that is not hyphen and digit
private static Regex MyMask = new Regex(@"[^\d-]");
private void inputSequential_KeyUp (object sender, KeyEventArgs e)
{
if (! String.IsNullOrEmpty (inputSequential.Text)
{
inputSequential.Text = MyMask.Replace (inputSequential.Text, "");
// MatchCollection matches = Regex.Matches (inputSequential.Text, "[\\ -]");
//
// if (matches.Count> 1)
// {
// for (int i = 1; i <= matches.Count - 1; i ++)
// {
// inputSequential.Text = inputSequential.Text.Substring (0, matches [i] .Index-1) + inputSequential.Text.Substring (matches [i] .Index, inputSequential.Text.Length);
// inputSequential.Text = inputSequential.Text.Replace (inputSequential.Text [matches [i] .Index] .ToString(), "");
//}
//}
}
}
預計:
如果你知道更好的方法來做到這一點,請讓我知道。 謝謝傾聽。
你這裏正則表達式是搞砸了。這是一個複製/粘貼錯誤? –
所以,你試圖捕獲一個序列:一個可選的':'和一個數字和'-'以外的字符。這是錯誤的。 –
在我的理解中,這個表達式拒絕非數字和連字符。結合替換我刪除不是連字符和數字的一切。 –