繁体   English   中英

如何检查字符串是否包含除字母和数字以外的任何字符?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM