微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

替换无效的文件名字符

如何解决替换无效的文件名字符

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

例如:

  • 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)。但是还有许多其他类似“空格”的字符。

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

解决方法

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

其次,您不能使用 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(']','\]')

,

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

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

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

$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]+

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。