【问题标题】:How to filter a string for invalid filename characters using regex如何使用正则表达式过滤字符串中的无效文件名字符
【发布时间】:2016-07-25 19:24:24
【问题描述】:

我的问题是我不希望用户输入任何错误,所以我试图删除它,我的问题是我制作了一个正则表达式,它删除了除单词之外的所有内容,并且还删除了 。 , - 但我需要这些标志来让用户开心: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'

【问题讨论】:

  • 如果你有特定的字符,把它们放到一个字符类中,为什么要使用一个通用的\W?使用[~"#%&amp;*:&lt;&gt;?/\\{|}]。但是,您还应该考虑 conlpt1 等文件名。
  • 好吧忘记它现在工作了谢谢你的支持:D
  • 然后我添加了评论作为答案。

标签: regex powershell powershell-2.0


【解决方案1】:

请注意,如果您想替换无效的文件名字符,您可以利用 How to strip illegal characters before trying to save filenames? 中的解决方案

回答您的问题,如果您有特定字符,请将它们放入字符类中,不要使用也匹配更多字符的通用 \W

使用

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

regex demo

请注意,除了\ 之外的所有这些字符都不需要在字符类中转义。此外,添加 + 量词(匹配 1 次或多次出现的量化子模式)简化了替换过程(匹配整个连续的字符块并用替换模式(此处为空字符串)一次替换所有字符)。

请注意,您可能还需要考虑 conlpt1 等文件名。

【讨论】:

    【解决方案2】:

    为确保文件名有效,应使用GetInvalidFileNameChars .NET 方法检索所有无效字符并使用正则表达式检查文件名是否有效:

    [regex]$containsInvalidCharacter = '[{0}]' -f ([regex]::Escape([System.IO.Path]::GetInvalidFileNameChars()))
    
    if ($containsInvalidCharacter.IsMatch(($ResearchGroupInbox.Text)))
    {
        # filename is invalid...
    }
    

    【讨论】:

      【解决方案3】:
      $ResearchGroupInbox.Text -replace '~|"|#|%|\&|\*|:|<|>|\?|\/|\\|{|\||}'
      

      或者如@Wiketor建议你可以将其排除在'[~"#%&amp;*:&lt;&gt;?/\\{|}]+'

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-10-13
        • 1970-01-01
        • 1970-01-01
        • 2020-09-12
        • 1970-01-01
        • 2011-06-24
        • 1970-01-01
        相关资源
        最近更新 更多