Skip to main content
 首页 » 编程设计

c#之如何修改此正则表达式,使其只匹配目录并排除文件

2024年02月25日31qq78292959

这是正则表达式模式:^\D:(\\\w.+(\\?))+$

〇理想匹配(预期):
C:\文件夹1\文件夹2
C:\文件夹1\文件夹2\

✖ 但它也匹配(实际):
C:\文件夹1\文件夹2\文件1.txt
C:\folder1\folder2\file2.docx

问题(使其与 OP 标题匹配):
我应该如何更改此正则表达式,使其包含上述文件示例中提到的文件?

或

子问题: 作为使用 Regex 的替代方法,您有什么建议吗?详情请引用下方。

详细场景:
在我的 WinForms 应用程序中,我有一个 TextBox,其中它的值是从配置文件加载的。值可以是任何东西——整数、字符串,甚至目录。如果它看起来像一个目录(这就是我使用正则表达式的原因),我想通过使用 System.IO.Directory.Exist() 来验证这个值。

请您参考如下方法:

我的猜测是,也许您正在尝试编写一个类似于以下内容的表达式:

^\D:(\\\w+\\\w+(\\?))$  

也许不是,我不太确定。

测试

using System; 
using System.Text.RegularExpressions; 
 
public class Example 
{ 
    public static void Main() 
    { 
        string pattern = @"^\D:(\\\w+\\\w+(\\?))$"; 
        string input = @"C:\folder1\folder2 
C:\folder1\folder2\ 
C:\folder1\folder2\file1.txt 
C:\folder1\folder2\file2.docx 
 
"; 
        RegexOptions options = RegexOptions.Multiline; 
         
        foreach (Match m in Regex.Matches(input, pattern, options)) 
        { 
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index); 
        } 
    } 
} 

If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


正则表达式电路

jex.im可视化正则表达式: