Reputation: 1520
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:
The if
condition returns False
and I can't figure out why.
The line with Regex.Replace(...)
throws an ArgumentException telling me (roughly translated) that, while analyzing the sequence ^.+\([^\]+)$
, there "was an unfinished [] clause".
My thoughts:
Any editor of my choice marks "C:\" as a match for the specified expression.
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
Reputation: 5132
Instead of using regular expressions to parse out path information, why not use System.IO.Path?
Upvotes: 3
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