c# - 检查文本框是否包含数字和字符串
问题描述
我是一名新程序员,我有一个项目,我希望文本框包含字母和至少 1 个数字。这是我的代码:
private void button1_Click(object sender, EventArgs e)
{
StreamWriter sw = File.AppendText("name.txt");
if (String.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Invalid name!\nPlease Try Again!");
}
else if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z ]*$") && System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[0-9]"))
{
MessageBox.Show("The field accepts only letters and at least one number!\nPlease Try Again");
}
else
{
sw.WriteLine(textBox1.Text);
MessageBox.Show("Player added Successfully!");
Form3 f3 = new Form3();
f3.Show();
}
sw.Close();
}
解决方案
要检查您的字符串是否仅包含数字和字母,您可以Char.IsLetterOrDigit()
结合使用String.All()
来检查该字符串中的所有字符是否与给定类型匹配。
此外,我还使用Char.IsDigit()
了 withString.Any()
来检查至少一个字符是否是数字。
例子:
string s = textBox1.Text;
// Check if all of the letters are only Letters and Digits
// and if atleast one is a Digit.
bool result = !s.All(Char.IsLetterOrDigit) || !s.Any(Char.IsDigit);
我还添加IsNullOrWhiteSpace
了一个检查用户是否输入了文本,但它只包含空格。此外,我将代码封装在 using 块中,以便它在离开 using 块后Streamwriter
自动调用该方法。Dispose()
代码中的示例:
using (StreamWriter sw = File.AppendText("name.txt")) {
string s = textBox1.Text;
// Check if string consits of only whitespaces, nothign or if it is null.
if (String.IsNullOrWhiteSpace(s)) {
MessageBox.Show("Invalid name!\nPlease Try Again!");
}
// Check if all of the letters are only Letters and Digits
// and if atleast one is a Digit.
else if (!s.All(Char.IsLetterOrDigit) || !s.Any(Char.IsDigit)) {
MessageBox.Show("The field accepts only letters and
+ at least one number!\nPlease Try Again");
}
else {
sw.WriteLine(s);
MessageBox.Show("Player added Successfully!");
Form3 f3 = new Form3();
f3.Show();
}
}
推荐阅读
- training-data - 将 mfcc 特征与训练标签相结合
- android - 为什么 TextView 没有显示在应用程序界面上?
- json - Spring数据中的MongoDB查询以按键查找地图对象
- python - QGraphicsPathItem 上的 QPropertyAnimation
- javascript - 使用 call() 的显式绑定如何在 Javascript 中工作?
- javascript - 如何使用 AJAX 和 Ruby on Rails 以新日期更新预订表?
- r - 在 R 中为自定义函数运行遗传算法时出错
- python - PyCharm 在重置后添加颜色反转 % 和新行
- javascript - React JS 组件在传递 props 时重新渲染,尽管有回调
- python - 用案例替换 Python 字符串