9db8f865b1d5f3e3978b37e7a3480cc4

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.

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 !

E4358a6dc7aea1d2b79045522c2dab52

Ryan

August 7, 2009, August 07, 2009 14:21, permalink

1 rating. Login to rate!

[java]

1
2
3
4
5
String s = ...
String regex1 = .*?classes/(.*?)\.class
s = s.replaceFirst(regex, "$1")
String regex2 = [\\/]
s = s.replaceAll(regex2, ".")
9db8f865b1d5f3e3978b37e7a3480cc4

mikenereson.blogspot.com

August 7, 2009, August 07, 2009 14:29, permalink

No rating. Login to rate!

Fixed slashes to handle more operating systems. Thanks Ryan.

1
2
3
file.getAbsolutePath()
  .replaceFirst(".*?classes[\\\\/](.*?)\\.class", "$1")
  .replaceAll("[\\\\/]", ".");
70b0265140eaff6e312eb3efcff3c195

Ben Atkin

August 8, 2009, August 08, 2009 00:03, permalink

1 rating. Login to rate!

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\\.)+", "");
    }
}
0706636fd5e30fa66019d7ffacdb5b11

Marco Valtas

August 12, 2009, August 12, 2009 03:10, permalink

1 rating. Login to rate!

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("\\\\" , ".")
		
		);
		
	}
}

Your refactoring





Format Copy from initial code

or Cancel