• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 526
  • Last Modified:

Regular expression only working in command prompt, not as variable

I want to check if a file name contains ~$ (tilde and dollar) as the first two characters, because then it's an Office backup file. That should be the following regular expression:  ^\x7E\x24

When I create a c# program where I have to type in the regular expression in the command prompt like this it works fine:
Enter regular expression: ^\x7E\x24
Enter input for comparison: ~$rbar i Nordic.doc

However, when I use the same regular expression as a string variable in a c# program where fi is FileInfo, it doesn't work:
string reTildeDollar = @"^\x7E\x24";
if (Regex.IsMatch(reTildeDollar, fi.Name))
                    Console.WriteLine("Office backup file - will not be copied");
                    this.CopyToSharepoint(currentDir.FullName,fi.Name, fi.LastWriteTime);

Can anybody tell me why? (and yes, some of the files start with ~$)
2 Solutions
Hi, it should be:
 if (Regex.IsMatch(fi.Name, reTildeDollar))

You have switched the order of the regex match parameters.
The first parameter should be the input string and the second one is the regex expression, not the oppssite.
Fernando SotoCommented:
Hi kasperEH;

It is because you have the parameters to the method backwards, it should be this.

Regex.IsMatch(fi.Name, reTildeDollar)

kasperEHAuthor Commented:
Thanks. I should have found that mistake myself :-)

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now