John Mills
John Mills

Reputation: 10263

Regular expression works in VB but not C#

I have the following regular expression for validating a file name:

^(([a-zA-Z]:|\)\)?(((.)|(..)|([^\/:*\?"\|<>. ](([^\/:*\?"\|<>. ])|([^\/:*\?"\|<>][^\/:*\?"\|<>. ]))?))\)[^\/:*\?"\|<>. ](([^\/:*\?"\|<>. ])|([^\/:*\?"\|<>]*[^\/:*\?"\|<>. ]))?$

I can get it to work in VB.NET but not C#. I can't figure out why it works in one but not the other.

VB code:

Regex.Matches("c:\temp\abc.exe", "^(([a-zA-Z]:|\\)\\)?(((\.)|(\.\.)|([^\\/:\*\?""\|<>\. ](([^\\/:\*\?""\|<>\. ])|([^\\/:\*\?""\|<>]*[^\\/:\*\?""\|<>\. ]))?))\\)*[^\\/:\*\?""\|<>\. ](([^\\/:\*\?""\|<>\. ])|([^\\/:\*\?""\|<>]*[^\\/:\*\?""\|<>\. ]))?$")

C# code:

Regex.Matches("c:\temp\abc.exe", @"^(([a-zA-Z]:|\\)\\)?(((\.)|(\.\.)|([^\\/:\*\?""\|<>\. ](([^\\/:\*\?""\|<>\. ])|([^\\/:\*\?""\|<>]*[^\\/:\*\?""\|<>\. ]))?))\\)*[^\\/:\*\?""\|<>\. ](([^\\/:\*\?""\|<>\. ])|([^\\/:\*\?""\|<>]*[^\\/:\*\?""\|<>\. ]))?$");

As far as I can tell the patterns are identical in both languages with escaping. When I run the VB code I get a match. When I run the C# code I get nothing.

Can anyone see what I'm missing?

Upvotes: 0

Views: 324

Answers (1)

Matthew Flaschen
Matthew Flaschen

Reputation: 284836

Don't you need to also escape the filename in C#? E.g:

@"c:\temp\abc.exe"

Upvotes: 17

Related Questions