简体   繁体   中英

replace all occurrences of . for normalization

Say I have the string "foo/./bar" then it should be normalized to "foo/bar". I tried doing this using the following regex:

String result = filePath.replaceAll("\\./", "");

but it didn't work out for me.. any idea?

In Java 7 there are built-in methods for this in the Path class. (If you're not using Java 7, then sorry.)

Either way, regexps are probably not the best way to implement path normalisation. It's a lot easier to do a split and then add the path elements to a stack, adding nothing when the element is . and popping if it's .. .

I guess what you want is to normalize a Windows filepath, not just to remove periods (in your example, you would have to remove a period and the following slash). So, why not use java.nio.Path ?

Path path = Paths.get(unnormalizedPath);
Path normalized = path.normalize();

Or with pre-Java7, you can do

new File(unnormalizedPath).getCanonicalPath();

Try this

System.out.println("./a/./b/c/."
                    .replaceAll("/[.]/|^[.]/","/")
                    .replaceAll("/[.]",""));

Output

/a/b/c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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