Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regular expression hard drive issue

Tags:

c#

regex

I'm trying to have a regular expression in a case of if the user chose a hard drive (e.g. "C:\" drive).
I've tried:

Match reg = Regex.Match(location, @"/[A-Z][:][\\]/");

And:

Match reg = Regex.Match(location, "/[A-Z][:][\\]/");

The 1st line doesn't detect, the 2nd line ends with an exception: System.ArgumentException

like image 427
avi12 Avatar asked Dec 25 '22 08:12

avi12


1 Answers

Presumably, you want to check that the string is exactly something like C:\, but not something like ABC:\\ and my dog. You need the anchors ^ and $:

^[A-Z]:\\$

In code:

foundMatch = Regex.IsMatch(yourstring, @"^[A-Z]:\\$");

Note that I have removed the brackets you had in [:] and [\\] (not necessary since in each of these cases we are matching a single literal character, not one character from a class of several possible characters).

like image 140
zx81 Avatar answered Jan 09 '23 06:01

zx81