i am trying to make my java program search in a directory for any other folders that contains the word "natives". I have all that working. But to insure more security i would also like it to check for numbers seeing the actual folder is called "1.7.4-natives-16411115736623".
All in all i want my java program to check if a directory with "natives" in the name. if so, check if the folder name contains a "-16411115736623" after the word natives. Keep in mind these numbers are random, but are always 14 digits.
Here is my current code:
'File folder = new File(System.getProperty("user.home")+File.separator+"/Library/Application Support/minecraft/versions/");
File[] listOfFiles = folder.listFiles();
outerloop:
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory()) {
String filePathString = (System.getProperty("user.home")+"/AppData/Roaming/.minecraft/versions/"+listOfFiles[i].getName()+"/");
File folder2 = new File(filePathString);
File[] listOfFiles2 = folder2.listFiles();
for (int f = 0; f < listOfFiles2.length; f++){
if(listOfFiles2[f].getName().contains("natives")) {
mcRunning = true;
System.out.println(listOfFiles2[f]);
System.out.println("Folder Exists");
Utils.verifyJars(filePathString);
}else{
System.out.println(listOfFiles2[f]);
System.out.println("Folder does Exist");
}
}
}
}'
Do both at the same time
There is no need for a second check. Regex allows you to check both that the folder names contains natives
, and that natives
is followed by a dash and 14 digits, in a single pass.
Use this regex: natives-\d{14}
Or, if the 14 digits must terminate the folder name, use natives-\d{14}$
(otherwise you could match some-natives-0123456789012311111 and my dog
)
To do this in your code, where you have if(listOfFiles2[f].getName().contains("natives"))
, you can use this instead:
// before the outer for loop
Pattern regex = Pattern.compile("natives-\\d{14}$");
// later
Matcher regexMatcher = regex.matcher(listOfFiles2[f].getName());
if(regexMatcher.find()) {... success ...}