2

As it mentioned in the topic, is there a way to change the String of a file's path in java? For example:

  String fileName = "scripts/css/an.main.master.css";

How can I just keep the file's name “an.main.master.css” and change the folder path "scripts/css" to whatever I want? In other word, how can I detect the last backslash(the substring after that slash will be the file's name, and the substring before that slash will be the path). I am thinking to using Regular Expression, but I am not good at this. Can anyone help?

1
  • You could use fileName.substring(fileName.lastIndexOf("/")++) Commented Jul 23, 2014 at 18:38

2 Answers 2

1

If regular expression is the way you want to go..

If you want to retain the last forward slash replacing everything before it:

String s = "scripts/css/an.main.master.css";
String r = s.replaceAll("^.*(?=/)", "foo");
// => "foo/an.main.master.css"

Or if you want the last forward slash removed as well:

String s = "scripts/css/an.main.master.css";
String r = s.replaceAll("^.*/", "foo/");
//=> "foo/an.main.master.css"
Sign up to request clarification or add additional context in comments.

Comments

1

REgex:

^(.*/)(.*)$

Replace:

string$2

string - string you want to replace.

Java code would be,

String fileName = "scripts/css/an.main.master.css";
String m1 = fileName.replaceAll("^(.*/)(.*)$", "string $2");
System.out.println(m1);

IDEONE

Comments

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.