3

I am finding a sub directories based on regular expression.

When i have following regex pattern, everything is working fine.

Dim sPattern As String = "^[/C:\/Users\/parth.jani\/Documents\/New folder\/b\/Photo_](.*)[_Order1]$"

But if i have following pattern, it throws [x-y] range in reverse order error.

Dim sPattern As String = "^[/C:\/Users\/parth.jani\/Documents\/New folder\/b\/Photo_](.*)[_Order-1]$"

I know its "-" character causing the error in

[_Order-1]$

If anyone could help, i'll be greatful. :-)

1 Answer 1

3

The hyphen - character has semantic meaning within a RegEx, especially when enclosed in []. If this is part of the file name you need to match, you should escape it using \-.

In general the usage of [] in your expression seems inappropriate to me, as it denotes a range of possible characters, not a sequence. If you need to treat their content as a separate group, use () instead, like this:

"^(C:\\Users\\parth.jani\\Documents\\New folder\\b\\Photo_)(.*)(_Order\-1)$"

If you are concerned about these not to be matched by the capturing groups (i.e. if you need to capture only the (.*) part) then add ?: in the beginning of the other groups so the matcher will ignore them:

"^(?:C:\\Users\\parth.jani\\Documents\\New folder\\b\\Photo_)(.*)(?:_Order\-1)$"

Notice I have changed the path separator from "\/" to "\\" as the former is invalid. If you still do not get matches, and you run this against files, check if your files have extensions. As the pattern stands now, it will expect the path to be without file extension (a directory name or a file with no ext). If you run your code against files with extensions retrieved in a way similar to Directory.GetAllFiles(), the call will include the file names with extensions, and the regex will not match them. I am adding this because if you use the default OS options on Windows, it hides the extensions of known file types, so your expected path might not be the one that the regex is evaluated against.

Sign up to request clarification or add additional context in comments.

3 Comments

I tried the solution you suggested, but its not giving me directory matched result. Regex.IsMatch always returns false even though directory name matches(eg. C:\Users\parth.jani\Documents\New folder\b\Photo_usr_Order-1)
@jparthj, I edited the regex. I got confused by your escape sequences - windows paths use "\" symbol, that is escaped this way "\\", not "\/". I tested the above code here, so it works: derekslager.com/blog/posts/2007/09/…
@lvaylo slavov: I am only fetching sub directories, not files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.