如何使 powershell 文本框只接受字母或数字字符?

How to make a powershell textbox accepts only alphabetical or numeric character?

我正在用 powershell 制作一个 windows 表单文本框,需要用户仅键入数字或字母字符。

我发现它在 c#

中使用
System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z ]")

可能有一种方法可以在 powershell 中调整它

我的部分代码

...
# TextBox
$textbox = New-Object System.Windows.Forms.TextBox
$textbox.AutoSize = $true
$textbox.Location = New-Object System.Drawing.Point(150,125)
$textbox.Name = 'textbox_sw'
$textbox.Size = New-Object System.Drawing.Size(220,20)
$textbox.Text = "Max11car"
$textbox.MaxLength = 11
$form.Add_Shown({$form.Activate(); $textbox.Focus()}) # donne le focus à la text box
#$textbox = New-Object System.Text.RegularExpressions.Regex.IsMatch($textbox.Text, "^[a-zA-Z0-9 ]")
#$textbox = New-Object System.Text.RegularExpressions.Regex($textbox.Text, "^[a-zA-Z0-9 ]")
...

我希望输出类似于 AbCDef45 而不是 Ab%$58

我建议您向文本框添加一个 Add_TextChanged() 方法,它会立即删除您不允许的任何字符。

像这样:

$textBox.Add_TextChanged({
    if ($this.Text -match '[^a-z 0-9]') {
        $cursorPos = $this.SelectionStart
        $this.Text = $this.Text -replace '[^a-z 0-9]',''
        # move the cursor to the end of the text:
        # $this.SelectionStart = $this.Text.Length

        # or leave the cursor where it was before the replace
        $this.SelectionStart = $cursorPos - 1
        $this.SelectionLength = 0
    }
})

正则表达式详细信息:

[^a-z 0-9]    Match a single character NOT present in the list below:
              - a character in the range between “a” and “z”
              - the space character “ ”
              - a character in the range between “0” and “9”