简体   繁体   English

Java Regex查找特定文件

[英]Java Regex to find particular file

In one of my test case I want to copy particular jar of a component from one location to another location. 在我的一个测试用例中,我想将组件的特定jar从一个位置复制到另一位置。 eg when target directory has only following jars 例如,当目标目录只有以下罐子时

org.test.custom.search-4.2.2-SNAPSHOT-.jar org.test.custom.search-4.2.2-SNAPSHOT-.jar
org.test.custom.search-4.2.2- tests -SNAPSHOT.jar org.test.custom.search-4.2.2- 测试 -SNAPSHOT.jar

I want to copy the org.test.custom.search-4.2.2-SNAPSHOT-.jar . 我想复制org.test.custom.search-4.2.2-SNAPSHOT-.jar。 Where version of this jar can be changed at any time . 可以随时更改此jar版本的位置。 So I can use the regex for that purpose as mentioned here[1]. 因此,我可以按照此处[1]的目的使用正则表达式。 But I want to know how to omit the other jar in regex. 但是我想知道如何省略正则表达式中的另一个jar。 ie want to omit the jar which has string " tests " in its name. 即要省略名称中带有字符串“ tests ”的罐子。

1. Regex for files in a directory 1. 用于目录中文件的正则表达式

You can use indexOf instead of regex to check if the file name containing the word "tests" like this: 您可以使用indexOf而不是regex来检查文件名是否包含单词“ tests”,如下所示:

if(fileName.indexOf("tests") >= 0) {
    // do what you want
}

Update: indexOf() will be much quicker than a regex , and is probably also easier to understand. 更新: indexOf()将比regex快得多,并且可能也更容易理解。

The regex based solution would be: 基于regex的解决方案是:

if (fileName.matches(".*tests.*")) {
    //do something
} else {
    //do something else
}

将SNAPSHOT与任何给定的版本号完全匹配,而忽略所有其他版本号(包括tests-SNAPSHOT):

org\.test\.custom\.search-\d+\.\d+\.\d+-SNAPSHOT-\.jar

One regex to match the main jar but not the test jar could be: 一个与主jar匹配但与测试jar不匹配的正则表达式可能是:

\w+-[\d.]+-(?!tests-).*\.jar

It has a negative matcher for the string "tests-". 它对字符串“ tests-”具有负匹配项。 Note that you'll have to escape the backslashes when you put this regex into a string. 请注意,将此正则表达式放入字符串中时,必须转义反斜杠。

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

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