Harti
Harti

Reputation: 1520

Regex that always returns false

Objective:

Use regular expressions to only display the actual folder name of a path. For instance,

C:\Users\Harti\GitHub

should be reduced to

GitHub

There is supposed to be a further rule to prevent users from entering a drive as a folder.


Issues:

  1. The if condition returns False and I can't figure out why.

  2. The line with Regex.Replace(...) throws an ArgumentException telling me (roughly translated) that, while analyzing the sequence ^.+\([^\]+)$, there "was an unfinished [] clause".


My thoughts:

  1. Any editor of my choice marks "C:\" as a match for the specified expression.

  2. The double backslash in the [^\\] may be treated as actually escaping the closing square bracket, therefore invalidating the regular expression. Using @"..." for the strings resulted in the same exception, however.


Can you please point me to whatever I may be missing? I'm completely new to VS and C#, so there may be anomalies I don't know about yet.

Code:

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);
    }
}

Upvotes: 1

Views: 306

Answers (2)

Edmund Schweppe
Edmund Schweppe

Reputation: 5132

Instead of using regular expressions to parse out path information, why not use System.IO.Path?

Upvotes: 3

Emanuele Paolini
Emanuele Paolini

Reputation: 10162

Probably you should write

string disallowedPattern = "^[A-Z]:\\\\$";

since the backslash must be escaped both in the regexp and in the C string literal.

Upvotes: 2

Related Questions