HOME       >>       Programming

Regular Expressions Not Matching


jimmy89

Hi All,
I am using Regular Expressions in VB.NET to find illegal filename characters in a string. The user enters and name, and it then saves the file with that name. I just need to make sure that the filename doesn't contain illegal filename characters.

The characters are / \ : ? " < > | (is there any others?)

I am using the following regex at the moment, but it doesn't seem to be picking up backslashes.

Dim myRegex As New System.Text.RegularExpressions.Regex("[\/:?'=<>|]")
Every other character it picks up, why just this one? Also the " character is illegal, how can i put that into the regex (at the moment it thinks its part of the code and not the regex)

If there is another way to do the same thing, or a different regex, that would be nice!

Thanks,
-jimmy

dserban

Have you tried escaping the \ with another \ - therefore making a \\ out of it?The same trick might work by putting a \" instead of the "The backslash is a good guess for what the escape character is in many environments, it might be that in VB.NET it's the same as well.


faulty.lee

For " you need to escape with " itself.

""


yordan

And of course you probably need to protect \ from itself (usually \ means "ignore what follows me"). So, instead of \ you should write down \\.I have this problem with the character $ in my script, I have to protect it, so instead of $ I write down \$.So, amongs things not to be used in a filename, I think that you should add the following ones :. (the dot, ".")+ (because on Unix systems a+b will try to calculate the sum of a and b )- (same reason, substracting)=(a=b will be evaluated as "does the variable a be equal to the variable b" or a syntax error)* (the star, means "everything" when interpreted by Unix or Linux)space (the blank, " ") because "my file" will try to write down a file namde "my" and a file named "my"$ (I guess, at least on IBM mainframe, but maybe your programs are not for mainframe ?) And I'm sure that other forumers here will tell you a lot of other forbidden characters.By the way, may I suggest you, if a blank or a minus is in the filename, replace it by _ (underscore) ? I see that other progs like 4image do it that way.


jimmy89

Thanks guys, those changes worked a treat! (I've never liked Regular Expressions, or maybe they haven't liked me) Yordan, thanks for the little extras - I've added them in also, you can never to too safe when it comes to end users and their inputs !Cheers,-jimmy



VIEW DESKTOP VERSION REGISTERGET FREE HOSTING

Xisto.com offers Free Web Hosting to its Members for their participation in this Community. We moderate all content posted here but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy. Copyright 2001-2019 by Xisto Corporation. All Rights Reserved.