如何使用正则表达式过滤包含无效文件名字符的字符串

3
我的问题是我不想让用户输入任何错误的内容,所以我试图删除它,我的问题是我制作了一个正则表达式,它可以除去除单词以外的所有内容,并且也会将、- 这些标志删除,但我需要这些标志来让用户感到开心:D
简而言之,此脚本使用正则表达式从输入字段中删除坏字符。
输入字段:
$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 

功能:

$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!
}

我不想出现的坏字符:

~ " # % & * : < > ? / \ { | } #those are the 'bad characters'

1
如果您有特定的字符,请将它们放入字符类中,为什么要使用通用的\W?请使用[~"#%&*:<>?/\\{|}]。但是,您还应该考虑像conlpt1等文件名。 - Wiktor Stribiżew
好的,算了,现在它正常工作了,谢谢你的支持 :D - Mister X CT
我随后将评论添加为答案。 - Wiktor Stribiżew
3个回答

4
请注意,如果您想替换无效的文件名字符,可以利用如何在尝试保存文件名之前去除非法字符?中的解决方案。
回答您的问题,如果您有特定的字符,请将它们放入字符类中,不要使用通用的\W,因为它还匹配了更多的字符。
使用

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

查看正则表达式演示

enter image description here

请注意,在字符类内部,除了\之外的所有这些字符都不需要转义。此外,添加+量词(匹配量化子模式的1个或多个出现)可以简化替换过程(匹配整个连续字符块,并一次性用替换模式(这里是空字符串)替换所有字符块)。
请注意,您可能还需要考虑像conlpt1等文件名。

3
为了确保文件名有效,您应该使用.NET方法GetInvalidFileNameChars来检索所有无效字符,并使用正则表达式检查文件名是否有效:
[regex]$containsInvalidCharacter = '[{0}]' -f ([regex]::Escape([System.IO.Path]::GetInvalidFileNameChars()))

if ($containsInvalidCharacter.IsMatch(($ResearchGroupInbox.Text)))
{
    # filename is invalid...
}

2
$ResearchGroupInbox.Text -replace '~|"|#|%|\&|\*|:|<|>|\?|\/|\\|{|\||}'

或者像@Wiketor建议的那样,您可以将其简化为'[~"#%&*:<>?/\\{|}]+'


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接