blade33
blade33

Reputation: 131

Regex to parse entire path?

Is there a regex which can parse a string which points to a file or folder (from the root e.g. C:)?

Language is Javascript.

Thanks

Upvotes: 3

Views: 657

Answers (2)

Jav_Rock
Jav_Rock

Reputation: 22245

Well, actually there are several, but it depends on what exactly you want to parse. Do you want something like: "C:/.../.../nameOfFile.extension"? Or without the name of the file? Can you be more specific about the problem? Which is the input?

I made this code, really simple, which for a given path, gives you the path without the root.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestProgram {

    static String path = "C:\\Folder1\\Folder2\\file.extension";

    private static void parsePath() {
      String newPath = "";
      String root = "C:";
      Matcher regexMatcher;
      regexMatcher = Pattern.compile("\\\\").matcher(path);
      newPath = regexMatcher.replaceAll("/");
      regexMatcher = Pattern.compile(root).matcher(newPath);
      newPath = regexMatcher.replaceAll("");    
      System.out.println(newPath);
    }

    public static void main(String[] args) {
       parsePath();    
    }
}

The output is:

/Folder1/Folder2/file.extension

I don't know if this is what you want, but you just have to play with methods. You will eventually reach the solution.

Upvotes: 2

josh.trow
josh.trow

Reputation: 4901

Why not skip the regex and just use split?

var path = "C:\\Users\\Joe.Blow\\Documents\\Pictures\\NotPr0n\\testimage1.jpg"
var arrPath = path.split("\\");
var filename = arrPath[arrPath.length - 1];
var drive = arrPath[0];

etc.

Upvotes: 2

Related Questions