F# 是否将多个后续无效字符转换为一个下划线?
以下字符串不是有效的文件名F# 是否将多个后续无效字符转换为一个下划线?,f#,F#,以下字符串不是有效的文件名 "File name\r\n\t\t\t\t\r\n\t\t\t\t (Revised 2018-05-31 15:35:41.16).txt" let fn = """File name (Revised 2018-05-31 15:35:41.16).txt""";; let invalid = System.IO.Path.GetInvalidFileNameChars();; String.Join("",
"File name\r\n\t\t\t\t\r\n\t\t\t\t (Revised 2018-05-31 15:35:41.16).txt"
let fn = """File name
(Revised 2018-05-31 15:35:41.16).txt""";;
let invalid = System.IO.Path.GetInvalidFileNameChars();;
String.Join("",
fn |> Seq.filter(fun x ->
not (Array.exists (fun y -> y = x) invalid)
)
)
// "File name (Revised 2018-05-31 153541.16).txt"
以下代码将其转换为有效的文件名
"File name\r\n\t\t\t\t\r\n\t\t\t\t (Revised 2018-05-31 15:35:41.16).txt"
let fn = """File name
(Revised 2018-05-31 15:35:41.16).txt""";;
let invalid = System.IO.Path.GetInvalidFileNameChars();;
String.Join("",
fn |> Seq.filter(fun x ->
not (Array.exists (fun y -> y = x) invalid)
)
)
// "File name (Revised 2018-05-31 153541.16).txt"
它只是删除这些无效字符。如何将这些无效代码转换为
?对于这些多个随后出现的无效字符,我希望它们只替换为一个\uu
。因此,预期的结果应该是
"File name_ (Revised 2018-05-31 15_35_41.16).txt"
这应该起作用:
open System.Text.RegularExpressions
let normalizeFileName name =
let invalidPattern =
System.IO.Path.GetInvalidFileNameChars()
|> Seq.map (string >> Regex.Escape)
|> String.concat ""
|> sprintf "[%s]+"
Regex.Replace(name, invalidPattern, "_")
用正则表达式替换这些字符的任何组合是这里最简单的事情;这与C#中的工作原理完全相同。因此,您需要大致类似于
Regex.Replace(fn,@“[\\n\\r\\t]+”,“\u”)
的东西。对,正则表达式应该是最简单的方法。只需要使用System.IO.Path.GetInvalidFileNameChars()构建模式。