简体   繁体   English

正则表达式忽略文件扩展名

[英]Regular expressions ignoring a file extension

I need some help with a regular expression. 我需要一些正则表达式帮助。 I have the following 4 file names 我有以下4个文件名

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 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. 基本上,我需要的是让我的正则表达式忽略文件末尾带有.gz的文件。 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 JS代码

 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 如果您只有phdtxt扩展名,则可以使用

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

Which means: a string starting with heapdump, followed by whatever, then a dot, then phd or txt, end of line 这意味着: 一个以heapdump开头的字符串,然后是任何东西,然后是一个点,然后是phd或txt,该行的末尾

Or you can simply negate a string that ends with dot gz 或者您可以简单地否定以点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 : 一个不需要使用正则表达式的选项是将句点( . )上的文件名拆分为一个数组,然后检查数组的最后一个元素是否包含扩展名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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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