1 2 3 4 5 6 7
String className = file.getAbsolutePath(); /* TODO, replace this with regex is possible */ className = className.substring(0, className.length() - 6); // chop off ".class" className = className.replace('/', '.'); className = className.replace('\\', '.'); className = className.substring(className.indexOf(CLASSES) + CLASSES.length());
Refactorings
No refactoring yet !
Ryan
August 7, 2009, August 07, 2009 14:21, permalink
[java]
1 2 3 4 5
String s = ... String regex1 = .*?classes/(.*?)\.class s = s.replaceFirst(regex, "$1") String regex2 = [\\/] s = s.replaceAll(regex2, ".")
mikenereson.blogspot.com
August 7, 2009, August 07, 2009 14:29, permalink
Fixed slashes to handle more operating systems. Thanks Ryan.
1 2 3
file.getAbsolutePath() .replaceFirst(".*?classes[\\\\/](.*?)\\.class", "$1") .replaceAll("[\\\\/]", ".");
Ben Atkin
August 8, 2009, August 08, 2009 00:03, permalink
Here's my take on it. I added an extra backslash in the filename to see if getAbsolutePath() sanitizes filenames. It doesn't, so I added a + to the separator regex. I also did the replacements differently.
1 2 3 4 5 6 7 8 9 10 11
import java.io.File; public class Path { public static void main(String[] args) { System.out.println(classFromFile(new File("c:\\dev\\svnlocal\\project\\target\\classes\\com\\\\company\\project\\File.class"))); } public static String classFromFile(File f) { return f.getAbsolutePath().replaceFirst("\\.class$", "").replaceAll("[\\\\/]+", ".").replaceFirst("^(.*classes\\.)+", ""); } }
Marco Valtas
August 12, 2009, August 12, 2009 03:10, permalink
Here's my example, use a simple backreference (http://www.regular-expressions.info/java.html) to capture the portion of the path you are interested, after that you substitute the "\" for "."
RegexpExample
1 2 3 4 5 6 7 8 9 10 11 12
public class RegExpExample { public static void main(String[] args) { System.out.println( "c:\\dev\\svnlocal\\project\\target\\classes\\com\\company\\project\\File.class" .replaceAll(".*classes\\\\(.*).class$","$1").replaceAll("\\\\" , ".") ); } }
Can this be refactored to use REGEX to make the format and replacement changes?
The goal is to turn
c:\dev\svnlocal\project\target\classes\com\company\project\File.class
into
com.company.project.File
It should also handle forward slashes.