-1

I am trying to use a variable in my regex pattern. This variable will always change and never be the same.

Whenever I try to use it in the pattern it gives me an error. Since the variable im using is a path, it sees "\" as an escape sequence and whichever letter as well so for example "c:\users" would be seen as "\u" which gives me an error.

I was wondering if there is any way around this, like i said this variable is always changing and hard coding any values wouldn't work.

Here is my existing code for the regex pattern:

public static Boolean validateFilePath(String dstPath, String newFileDstPath)
{
   Boolean blnflag = false;
   Match m = Regex.Match(newFileDstPath, @""+ dstPath + "");

   if (m.Success)
   {
      blnflag = true;
   }
   return blnflag;
}
Brandon
  • 645
  • 5
  • 13

2 Answers2

6

Use the Regex.Escape method? See http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape(v=vs.110).aspx

sovemp
  • 1,402
  • 1
  • 13
  • 31
1

If you READ THE DOCUMENTATION, you will discover the method Regex.Escape(), which will probably serve your purpose.

Some other notes:

  • Why are you doing this: @"" + dstPath + "" That resolves to dstPath, unchanged.

  • Why are you trying to use regular expressions for something that might be better addressed by using string.StartsWith() and/or the method and properties of System.IO.Path

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135