Home
TeamSite
RegEx - All Except Files ...
Gregg Faus
I haven't done much regex work in the past few months and haven't been able to get this one yet. I need a regex that accepts filenames with any given extension except certain types.
For instance, if I want to disallow .pdf, .zip extension what regex what match the follow test cases:
Target String:
default.asp
Match
Target String:
downloadme.pdf
No match
Target String:
archive.zip
No match
Target String:
readme.html
Match
Only the file names themselves will be matched against (no directory structure, etc). Any help would be appreciated. This will help support a download feature I'm working on to customize ContentCenter.
Find more posts tagged with
Comments
Adam Stoller
You didn't provide the context - but generally it would be something like this:
if ($targetString !~ /\.(pdf|zip)$/){
...process...
}
else { # optional
...skip...
}
--fish
Senior Consultant, Quotient Inc.
http://www.quotient-inc.com
Gregg Faus
I'd being using it in Java, but the regex would still be the same.
if (filterPattern.matcher(f.getPath()).matches()) {
# process file
}
# else do nothing
The filterPattern variable could be either a set of extensions to include or exclude depening on user input. I've got my include pattern working fine:
(.*\.aspx$|.*\.gif$)
// Include
But the same code could except a pattern to exclude certain files.
Hope this provides enough info.
Adam Stoller
Given that - why not just negate it:
if (
!
filterPattern.matcher(f.getPath()).matches(/\.(pdf|zip)$/)) {
# process file
}
# else do nothing
(
I'm not sure of the Java syntax - perhaps you need quotes around the expression?
)
--fish
Senior Consultant, Quotient Inc.
http://www.quotient-inc.com
Gregg Faus
Ghoti,
I got it working now. I changed my match call so that it would process a file if it found any match within the text like so:
//String filterRegex = "(.*\\.aspx$|.*\\.gif$)"; // Include
String filterRegex = ".*\\.(?!gif$|asp$)"; // Exclude
filterPattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
if (filterPattern.matcher(f.getName()).find()) {
// Process file
}
In this case, I'm trying to include just certain files, but if I uncommented the other regex, it would work in the reverse role -- it would exclude certain file types.
Thanks for the help.