3

到目前为止,这就是我所拥有的,但我在任何地方都找不到代码说我只想包含字母和数字。我不熟悉正则表达式。现在,即使我包含“#”,我的代码也会忽略 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.");
        }
    }
}
4

4 回答 4

5

您可以使用该方法char.IsLetterOrDigit检查输入字符串是否仅包含字母或数字:

if (input.All(char.IsLetterOrDigit))
{
    //Only contains letters and digits
    ... 
}
于 2013-07-24T16:42:15.153 回答
2

您可以使用此模式:

@"^[^\W_]*$"

^并且$是字符串开始和结束的锚点。

由于\w代表所有字母、所有数字和下划线,因此您必须从字符类中删除下划线。

于 2013-07-24T16:42:29.957 回答
2

当您检查无效文件名时,我会使用Path.GetInvalidPathChars代替:

char[] invalidChars = Path.GetInvalidPathChars();
if (!input.All(c => !invalidChars.Contains(c)))
{
    //invalid file name
于 2013-07-24T16:49:50.430 回答
2

这将只允许字母和数字:

^[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.");
        }
    }
于 2013-07-24T16:50:13.557 回答