替换无效的文件名字符

时间:2021-06-08 09:05:06

标签: regex powershell

我想编写一个小实用函数,用破折号替换文件名中的任何禁止字符序列

例如:

  • foo.txt ==> foo.txt
  • Some string \o/ ==> Some string -o-
  • https://stackoverflow.com/questions ==> https-stackoverflow.com-questions

我这样写函数:

function Get-SafeFileName{
    param(
        [Parameter(Mandatory, Position=0, ValueFromPipeline)]
        [object]$Data
    )
    process {
    
        $pattern = "[" + [regex]::Escape([string][System.IO.Path]::GetInvalidFileNameChars()) +"]+"

        [regex]::Replace($Data, $pattern, "-")
    }
}

这是有效的,除了空格字符被替换,即使它是允许的字符。

This is a string 导致 This-is-a-string,这是不必要的。

如何解决这个问题?

挖掘一下表明 [System.IO.Path]::GetInvalidFileNameChars() 不包含空格字符(ASCII 代码 32)。但是还有许多其他类似“空格”的字符。

也许正则表达式引擎看不出区别?

2 个答案:

答案 0 :(得分:2)

首先,您通过将无效字符列表强制转换为字符串来错误地转换无效字符列表,这是字符类中出现空格的地方。

其次,您不能使用 Regex.Escape 转义字符类的字符,因为它旨在转义字符类外部必须是文字的字符。 >

修复是

function Get-SafeFileName{
    param(
        [Parameter(Mandatory, Position=0, ValueFromPipeline)]
        [object]$Data
    )
    process {
    
        $pattern = '[' + ([System.IO.Path]::GetInvalidFileNameChars() -join '').Replace('\','\\') + ']+'

        [regex]::Replace($Data, $pattern, "-")
    }
}

字符类中唯一需要转义的字符是:

  • ^
  • -
  • \
  • ]

由于 GetInvalidFileNameChars() 只包含提到的四个特殊字符之一,您可以只使用一个 .Replace('\', '\\') 而不是所有四个 .Replace('\','\\') .Replace('-','\-').Replace('^','\^').Replace(']','\]')

答案 1 :(得分:0)

我找到了另一种使用 unicode 构造的方法

function Get-SafeFileName{
    param(
        [Parameter(Mandatory, Position=0, ValueFromPipeline)]
        [object]$Data
    )
    process {
    
        $pattern = "[" + ( ([System.IO.Path]::GetInvalidFileNameChars() | % { "\x" + ([int]$_).ToString('X2') } ) -join '') +"]+"

        [regex]::Replace($Data, $pattern, "-")
    }
}

$pattern 现在是 [\x22\x3C\x3E\x7C\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x3A\x2A\x3F\x5C\x2F]+

有了这个,就没有歧义了。标准空格不会被替换