簡體   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