正则表达式验证文件名

发布于 2024-09-16 15:47:50 字数 88 浏览 0 评论 0原文

如果文件名有其他字符,则此 a-zA-Z0-9!@$%^&*()_+=-[]{}';,. 我们必须用某些字符替换它们或删除它们。

If filename has another characters then this a-zA-Z0-9!@$%^&*()_+=-[]{}';,.
we must replace them in some character or delete.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

初相遇 2024-09-23 15:47:50
resultString = Regex.Replace(subjectString, @"[^a-zA-Z0-9!@$%^&*()_+=[\]{}';,.-]", "X");

应该这样做。

说明:我复制了您的字符列表并将它们粘贴到 否定字符类 (<代码>[^...])。我只需要做两个小修改:转义右括号 (\]) 并将破折号放在字符串末尾。

resultString = Regex.Replace(subjectString, @"[^a-zA-Z0-9!@$%^&*()_+=[\]{}';,.-]", "X");

should do it.

Explanation: I copied your list of characters and pasted them into a negated character class ([^...]). I just had to make two minor modifications: Escaping the closing bracket (\]) and putting the dash at the end of the string.

待天淡蓝洁白时 2024-09-23 15:47:50
using System.Linq;
using System.IO;

string path = ...;

IEnumerable<char> invalidChars = Enumerable.Concat(
    Path.GetInvalidFileNameChars(),
    Path.GetInvalidPathChars());

foreach (char c in invalidChars)
{
    path = path.Replace(c, ''); // or any char you want
}
using System.Linq;
using System.IO;

string path = ...;

IEnumerable<char> invalidChars = Enumerable.Concat(
    Path.GetInvalidFileNameChars(),
    Path.GetInvalidPathChars());

foreach (char c in invalidChars)
{
    path = path.Replace(c, ''); // or any char you want
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文