【问题标题】:Single regex for folder path validation (Remote Path,FTP Path,Local System Folder Path,etc.,) in c# [closed]c# 中用于文件夹路径验证(远程路径、FTP 路径、本地系统文件夹路径等)的单个正则表达式 [关闭]
【发布时间】:2016-04-14 00:05:53
【问题描述】:

我想要一个正则表达式用于 C# 中的文件夹路径验证(远程路径、FTP 路径、本地系统文件夹路径等)。

例子:

  1. c:\folder one\folder2\folder 3
  2. \\remoteMachine\folder1
  3. \\1.22.33.444\folder 1\folder2
  4. ftp://12.123.112.231/
  5. C:\Program Files\Google\Chrome

【问题讨论】:

标签: c# regex path directory


【解决方案1】:

试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            string[] inputs = {
                  @"c:\folder one\folder2\folder 3",
                  @"\\remoteMachine\folder1",
                  @"\\1.22.33.444\folder 1\folder2",
                  @"ftp://12.123.112.231/",
                  @"C:\Program Files\Google\Chrome"
                             };
            string ip = @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}";
            string pattern = string.Format( @"^[A-Z]:(\\(\w+\s*)+)+" + // filename
                             @"|^\\\\{0}(\\(\w+\s*)+)+" +              // url with ip
                             @"|^\\(\\(\w+\s*)+)+" +                   // network filename \\abc\def
                             @"|^FTP://{0}/" +                         // ftp with ip
                             @"|^FTP://[A-Z]\w+/", ip);                // ftp with hostname


            foreach (string input in inputs)
            {
                bool match = Regex.IsMatch(input,pattern, RegexOptions.IgnoreCase);
                Console.WriteLine("\"{0}\" {1}", input, match? "matches" : "does not match");
            }
            Console.ReadLine();
        }
    }
}
​

【讨论】:

  • 试着解释你的答案...
  • 有什么需要解释的?对于任何了解基本正则表达式的人来说,这是显而易见的。大多数关于 Regex 的帖子,该人都知道 Regex,但无法弄清楚确切的语法。
  • “什么需要解释?” - 你编写的正则表达式背后的想法,所以有人可以验证他们是否正确地实现了这些原则,如果他们以后发现的话,可以改进它们邮政。例如,支持使用主机名而不是 IP 的 FTP URI。请阅读here我对“试试这个”答案的立场。您不必同意,我只是想解释一下,我认为没有解释的转储代码对其他人可能没有您想的那么有用。
  • 添加了 cmets 并包含了带有主机名的 FTP。
  • jdweng 感谢工作正常 ....
猜你喜欢
  • 1970-01-01
  • 2019-07-30
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多