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

时间:2013-07-24 16:39:55

标签: c# regex string validation

这是我到目前为止所拥有的,但我无法在任何地方找到代码来说我只想包含字母和数字。我不熟悉正则表达式。现在我的代码只是忽略了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 个答案:

答案 0 :(得分:5)

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

if (input.All(char.IsLetterOrDigit))
{
    //Only contains letters and digits
    ... 
}

答案 1 :(得分:2)

您可以使用此模式:

@"^[^\W_]*$"

^$是字符串开头和结尾的锚点。

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

答案 2 :(得分:2)

当您检查无效的文件名时,我会改为使用Path.GetInvalidPathChars

char[] invalidChars = Path.GetInvalidPathChars();
if (!input.All(c => !invalidChars.Contains(c)))
{
    //invalid file name

答案 3 :(得分:2)

这只会允许字母和数字:

^[a-zA-Z0-9]+$

检查website关于正则表达式的所有内容。

如果您想使用正则表达式,可以将其放在按钮点击事件中: - 确保导入适当的命名空间 - 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.");
        }
    }