diCoder
diCoder

Reputation: 191

change the String of a file'path in Java

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?

Upvotes: 2

Views: 1427

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174706

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

Upvotes: 1

hwnd
hwnd

Reputation: 70732

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"

Upvotes: 1

Related Questions