I have a directory with lots of folders, sub-folder and all with files in them. The idea of my project is to recurse through the entire directory, gather up all the names of the files and replace invalid characters (invalid for a SharePoint migration).
我有一个目录,里面有很多文件夹,子文件夹和文件。我的项目的想法是递归遍历整个目录,收集所有文件的名称并替换无效字符(对于SharePoint迁移无效)。
However, I'm completely unfamiliar with Regular Expressions. The characters i need to get rid in filenames are: ~, #, %, &, *, { } , \, /, :, <>, ?, -, |
and ""
I want to replace these characters with a blank space. I was hoping to use a string.replace()
method to look through all these file names and do the replacement.
然而,我对正则表达式完全不熟悉。文件名中需要删除的字符是:~、#、%、&、*、{}、\、/、:、<>、?、-、|和“我想用空格替换这些字符。”我希望使用string.replace()方法检查所有这些文件名并进行替换。
So far, the only code I've gotten to is the recursion. I was thinking of the recursion scanning the drive, fetching the names of these files and putting them in a List<string>
.
到目前为止,我得到的唯一代码是递归。我正在考虑递归扫描驱动器,获取这些文件的名称并将它们放入列表
Can anybody help me with how to find/replace invalid chars with RegEx with those specific characters?
谁能帮我找到/用正则表达式替换无效字符吗?
2 个解决方案
#1
42
string pattern = "[\\~#%&*{}/:<>?|\"-]";
string replacement = " ";
Regex regEx = new Regex(pattern);
string sanitized = Regex.Replace(regEx.Replace(input, replacement), @"\s+", " ");
This will replace runs of whitespace with a single space as well.
这也将用一个空格替换空白的运行。
#2
7
is there a way to get rid of extra spaces?
有没有办法摆脱多余的空间?
Try something like this:
试试这样:
string pattern = " *[\\~#%&*{}/:<>?|\"-]+ *";
string replacement = " ";
Regex regEx = new Regex(pattern);
string sanitized = regEx.Replace(input, replacement);
Consider learning a bit about regular expressions yourself, as it's also very useful in developing (e.g. search/replace in Visual Studio).
考虑自己学习一些正则表达式,因为它在开发(例如在Visual Studio中搜索/替换)时也非常有用。
#1
42
string pattern = "[\\~#%&*{}/:<>?|\"-]";
string replacement = " ";
Regex regEx = new Regex(pattern);
string sanitized = Regex.Replace(regEx.Replace(input, replacement), @"\s+", " ");
This will replace runs of whitespace with a single space as well.
这也将用一个空格替换空白的运行。
#2
7
is there a way to get rid of extra spaces?
有没有办法摆脱多余的空间?
Try something like this:
试试这样:
string pattern = " *[\\~#%&*{}/:<>?|\"-]+ *";
string replacement = " ";
Regex regEx = new Regex(pattern);
string sanitized = regEx.Replace(input, replacement);
Consider learning a bit about regular expressions yourself, as it's also very useful in developing (e.g. search/replace in Visual Studio).
考虑自己学习一些正则表达式,因为它在开发(例如在Visual Studio中搜索/替换)时也非常有用。