[英]How do I check that a string doesn't include any characters other than letters and numbers?
这是我到目前为止所做的,但我无法找到任何代码来说我只想包含字母和数字。 我不熟悉正则表达式。 现在我的代码只是忽略了while循环,即使我包含'#'。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void okBtn_Click(object sender, EventArgs e)
{
if(textBox1.Text.Contains(@"^[^\W_]*$"))
{
fm1.txtFileName = textBox1.Text;
this.Close();
}
else
{
MessageBox.Show("Filename cannot include illegal characters.");
}
}
}
您可以使用方法char.IsLetterOrDigit
来检查输入字符串是否只包含字母或数字:
if (input.All(char.IsLetterOrDigit))
{
//Only contains letters and digits
...
}
您可以使用此模式:
@"^[^\W_]*$"
^
和$
是字符串开头和结尾的锚点。
由于\\w
代表所有字母,所有数字和下划线,因此必须从字符类中删除下划线。
当您检查无效的文件名时,我会使用Path.GetInvalidPathChars :
char[] invalidChars = Path.GetInvalidPathChars();
if (!input.All(c => !invalidChars.Contains(c)))
{
//invalid file name
这只会允许字母和数字:
^[a-zA-Z0-9]+$
查看本网站所有关于正则表达式。
如果你想使用正则表达式,你可以将它放在你的按钮点击事件中: - 确保导入正确的命名空间 - using System.Text.RegularExpressions;
private void okBtn_Click(object sender, EventArgs e)
{
Match match = Regex.Match(textBox1.Text, @"^[a-zA-Z0-9]+$");
if (match.Success)
{
fm1.txtFileName = textBox1.Text;
this.Close();
}
else
{
MessageBox.Show("Filename cannot include illegal characters.");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.