0

I need to extract up to the directory a file is in, in the folder path. To do so, I created a simple regex. Here is an example path \\myvdi\Prod\2014\10\LTCG\LTCG_v2306_03_07_2014_1226.pfd

The regex below will find exactly what I need, but my problem is storing it into a variable. This is what I have below. It fails at the string array

  String[] temp = targetFile.split("\\.*\\");
  folder = temp[0];

Suggestions?

Thanks!

Edit The exception being thrown is: java.util.regex.PatternSyntaxException: Unexpected internal error near index 4

5
  • 1
    It fails at the string array How does it fail? What errors you see? Commented Mar 10, 2014 at 15:04
  • Also what output/result you ware expecting? Commented Mar 10, 2014 at 15:07
  • I am expecting this as an output: \\myvdi\Prod\2014\10\LTCG\ Commented Mar 10, 2014 at 15:14
  • As to what errors I see, an exception is thrown. Commented Mar 10, 2014 at 15:15
  • Edit your question and add stacktrace of thrown exception there. Commented Mar 10, 2014 at 15:16

3 Answers 3

2

If your path is valid within your file system, I would recommend not using regex and using a File object instead:

String path = "\\myvdi\\Prod\\2014\\10\\LTCG\\LTCG_v2306_03_07_2014_1226.pfd";
File file = new File(path);
System.out.println(file.getParent());

Output

\\myvdi\\Prod\\2014\\10\\LTCG\\
3
  • what are the advantages of this one? Commented Mar 10, 2014 at 15:30
  • Amongst the advantages, you are using the appropriate API objects and methods, with means to validate and control the actual object pointed at, which is a File. Also you can validate whether it exists or not, is accessible or not, etc. etc. Commented Mar 10, 2014 at 15:32
  • Even though I select another's answer to be what I was looking for (a direct answer to my question), I will be using this in another place in my code. So thank you! Commented Mar 10, 2014 at 17:57
0

Simply, you need:

String path = "\\myvdi\\Prod\\2014\\10\\LTCG\\LTCG_v2306_03_07_2014_1226.pfd";
String dir = path.substring(0, path.lastIndexOf("\\") + 1);
2
  • what does msg refer to? Commented Mar 10, 2014 at 15:12
  • Sorry i meant your path String. Commented Mar 10, 2014 at 15:13
0

You should use Pattern & Matchers which are much more powerful; from your description I'm not sure if you want to get the whole folder path, but if it is, here is a solution:

String s = "\\\\myvdi\\Prod\\2014\\10\\LTCG\\LTCG_v2306_03_07_2014_1226.pfd";

Pattern p = Pattern.compile("^(\\\\+[a-zA-Z0-9_-]+\\\\+([a-zA-Z0-9_-]+\\\\+)+).+$");
Matcher m = p.matcher(s);
if(m.matches()){

  System.out.println(m.group(m.groupCount()-1));
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.