简体   繁体   中英

Regular expressions ignoring a file extension

I need some help with a regular expression. I have the following 4 file names

heapdump.20160406.214053.18914.0013.phd heapdump.20160406.214053.18914.0013.phd.gz javacore.20160406.214053.18914.0002.txt javacore.20160406.214053.18914.0002.txt.gz

Basically what I need is for my regular expression to ignore the files with the .gz on the end of it. I tried the following but it does not seem to work.

/heapdump.*.phd|javacore.*.txt/i
/heapdump*.phd|javacore*.txt/i
/heapdump.\d+.\d+.\d+.\d+.phd|javacore.\d+.\d+.\d+.\d+.txt/i

Thanks

This will work

(?!.*\.gz$)(^.*$)

Regex Demo

JS Code

 var re = /(?!.*\\.gz$)(^.*$)/gm; var str = 'heapdump.20160406.214053.18914.0013.phd\\nheapdump.20160406.214053.18914.0013.phd.gz\\njavacore.20160406.214053.18914.0002.txt\\njavacore.20160406.214053.18914.0002.txt.gz'; var result = str.match(re); document.writeln(result) 

It depends on how much you want the solution to be precise. If you only have phd and txt extensions this will work

/heapdump.*\.(phd|txt)$/

Which means: a string starting with heapdump, followed by whatever, then a dot, then phd or txt, end of line

Or you can simply negate a string that ends with dot gz

/.*\.gz$/

One option which does not require using a regular expression would be to split the filename on period ( . ) into an array, and then check if the last element of the array contains the extension gz :

var filename = "heapdump.20160406.214053.18914.0013.phd.gz";
var parts = filename.split(".");

if (parts[parts.length - 1] == 'gz') {
    alert("ignore this file");
}
else {
    alert("pay attention to this file");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM