Skip to main content
 首页 » 编程设计

c#之总是返回 false 的正则表达式

2024年02月01日29lvdongjie

目标:

使用正则表达式仅显示路径的实际文件夹名称。例如,

C:\Users\Harti\GitHub 

应该减少到

GitHub 

应该有进一步的规则来防止用户将驱动器作为文件夹输入。


问题:

  1. if 条件返回 False,我不知道为什么。

  2. 在分析序列 ^.+\([^\]+)$,“有一个未完成的 [] 子句”。


我的想法:

  1. 我选择的任何编辑器都将“C:\”标记为指定表达式的匹配项。

  2. [^\\] 中的双反斜杠可能被视为实际转义右方括号,因此使正则表达式无效。但是,对字符串使用 @"..." 会导致相同的异常。


你能指出我可能遗漏的任何内容吗?我是 VS 和 C# 的新手,所以可能存在我还不知道的异常情况。

代码:

static void Main(string[] args) 
{ 
    string folderPath = "C:\\"; 
    string disallowedPattern = "^[A-Z]:\\$"; 
 
    if (Regex.IsMatch(folderPath, disallowedPattern)) 
    { 
        Console.WriteLine("You chose a drive! Not cool!"); 
    } 
    else 
    { 
        string suggestedProjectName = Regex.Replace(folderPath, "^.+\\([^\\]+)$", "$1"); 
        Console.WriteLine(suggestedProjectName); 
    } 
} 

请您参考如下方法:

为什么不用正则表达式解析出路径信息,为什么不用System.IO.Path呢? ?