Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 398
blade33 Avatar asked Nov 22 '25 07:11

blade33


2 Answers

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.

like image 82
josh.trow Avatar answered Nov 23 '25 20:11

josh.trow


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.

like image 35
Jav_Rock Avatar answered Nov 23 '25 22:11

Jav_Rock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!