3

My problem is that I don't want the user to type in anything wrong so I am trying to remove it and my problem is that I made a regex which removes everything except words and that also remove . , - but I need these signs to make the user happy :D

In a short summary: This Script removes bad characters in an input field using a regex.

Input field:

$CustomerInbox = New-Object System.Windows.Forms.TextBox #initialization -> initializes the input box
$CustomerInbox.Location = New-Object System.Drawing.Size(10,120) #Location -> where the label is located in the window
$CustomerInbox.Size = New-Object System.Drawing.Size(260,20) #Size -> defines the size of the inputbox
$CustomerInbox.MaxLength = 30 #sets max. length of the input box to 30
$CustomerInbox.add_TextChanged($CustomerInbox_OnTextEnter)
$objForm.Controls.Add($CustomerInbox) #adding -> adds the input box to the window 

Function:

$ResearchGroupInbox_OnTextEnter = {
if ($ResearchGroupInbox.Text -notmatch '^\w{1,6}$') { #regex (Regular Expression) to check if it does match numbers, words or non of them!
    $ResearchGroupInbox.Text = $ResearchGroupInbox.Text -replace '\W' #replaces all non words!
}

}

Bad Characters I don't want to appear:

~ " # % & * : < > ? / \ { | } #those are the 'bad characters'
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
Mister X CT
  • 163
  • 1
  • 11

3 Answers3

4

Note that if you want to replace invalid file name chars, you could leverage the solution from How to strip illegal characters before trying to save filenames?

Answering your question, if you have specific characters, put them into a character class, do not use a generic \W that also matches a lot more characters.

Use

[~"#%&*:<>?/\\{|}]+

See the regex demo

enter image description here

Note that all these chars except for \ do not need escaping inside a character class. Also, adding the + quantifier (matches 1 or more occurrences of the quantified subpattern) streamlines the replacing process (matches whole consecutive chunks of characters and replaced all of them at once with the replacement pattern (here, empty string)).

Note you may also need to account for filenames like con, lpt1, etc.

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
3

To ensure the filename is valid, you should use the GetInvalidFileNameChars .NET method to retrieve all invalid character and use a regex to check whether the filename is valid:

[regex]$containsInvalidCharacter = '[{0}]' -f ([regex]::Escape([System.IO.Path]::GetInvalidFileNameChars()))

if ($containsInvalidCharacter.IsMatch(($ResearchGroupInbox.Text)))
{
    # filename is invalid...
}
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
2
$ResearchGroupInbox.Text -replace '~|"|#|%|\&|\*|:|<|>|\?|\/|\\|{|\||}'

Or as @Wiketor suggest you can obviate it to '[~"#%&*:<>?/\\{|}]+'

Richard
  • 6,812
  • 5
  • 45
  • 60