假设textBox1为输入框,假设textBox2为输出框,button1为按钮. 程序需要引用
using System.Text.RegularExpressions;
private void button1_Click(object sender, EventArgs e)
{
string txt_1 = textBox1.Text;
int xx=0;
Regex rgx = new Regex("^0[0-9]{3}$"); //判断数字是否为4位,第一位是否为0
if (rgx.IsMatch(txt_1))
{
//减一并转换进制
xx = int.Parse(txt_1);
xx--;
textBox2.Text = xx.ToString("X");
}
else
{
MessageBox.Show("字符串输入错误");
}
}
------------------------------
程序Visual Studio2010编译通过
写TextBox的TextChanged事件
private string text = "";
private string patten = @"^0[0-9]{3}*$";
private void TxtWord_TextChanged(object sender, EventArgs e)
{
string word = ((TextBox)sender).Text.Trim();
if (word != "")
{
Match match = Regex.Match(word, patten);//匹配正则表达式
if (match.Success)//成功就赋值
{
text = word;//如果是合格就保存下来
}
((TextBox)sender).Text = text;//不成功就等于原来的数
((TextBox)sender).SelectionStart = ((TextBox)sender).Text.Length;//把鼠标移到最后面
}
else//不为空则清空text
{
text = "";
}
}