Reputation: 395
Hi I am new to reg expressions and I am trying to rename complicated file names like this one below:
3-M-COLORADOW-22017DB-LABEL
I want to rename this file name to this using java reg expressions:
3-M-COLORADOW-LABEL
However with my current beginning knowledge of Java Reg expressions I have only gotten this far:
I have tried many combinations with no success.I just need help finding the right combination of java reg expressions to achieve my goal. Basically i am trying to take one of the (dashes out). Any help would be appreciated.
for(File file:filesInDir) {
//x++;
String name = file.getName();
String newName = name;
String sameName = name;
if (name.contains("LABEL")){
newName = sameName.replaceAll("(.*)-(.*)(-LABEL)", "$1$3") ;
System.out.println(newName); // prints prints to file
String newPath = absolutePathOne + "\\" + newName;
file.renameTo(new File(newPath));
}
}
Upvotes: 0
Views: 83
Reputation: 3381
Since you didn't give much information about the structure of your filenames, i'll assume you want to filter out numbers followed by letters. You could use the following regex:
(.*)-\d+\D+(-.*) // java-syntax: "(.*)-\\d+\\D+(-.*)"
with a Matcher
.
Pattern pattern = Pattern.compile("(.*)-\\d+\\D+(-.*)");
Matcher matcher = pattern.matcher(oldFilename);
if (matcher.matches) {
String newFilename = m.group(1) + m.group(2);
}
Upvotes: 1
Reputation: 59978
You can use replaceAll with groups like this :
String str = "3-M-COLORADOW-22017DB-LABEL".replaceAll("(.*)-(.*)(-LABEL)", "$1$3");
Output
3-M-COLORADOW-LABEL
Upvotes: 2