Home > Mobile >  Replace first part of string in Java
Replace first part of string in Java

Time:09-17

I have the following String:

String myString = "/folder1/folder2/file.txt";

How can I replace the first part of the path wifolder1 with newFolder? I've tried the following (posted here: Remove first folder in string) but it doesn't do anything, the regex may need tweaked?

String newString = myString.replaceAll("/^.  ?[/]/", "newFolder");
// Expect newString = "/newFolder/folder2/file.txt"

Related question which uses Path to do this, I'd like to stick with String for my solution:

Replace first part of a Java Path

CodePudding user response:

here is the solution without regex:

String string = "/folder1/folder2/file.txt";
String revisedString = string.replace("folder1", "newFolder");
System.out.println(revisedString); // it will print -> /newFolder/folder2/file.txt

with regex:

String string = "/folder1/folder2/file.txt";
String revisedString  = string.replaceAll("^/[^/] /", "/newFolder/");
System.out.println(revisedString ); // it will print -> /newFolder/folder2/file.txt

CodePudding user response:

You need not even use Regular Expressions. You can directly do that by using the replace() method present in String class in Java.

String myString = "/folder1/folder2/file.txt";
String folder1 = "qualified and valid name";
String newLocation = myString.replace(folder1,newFolderName);

This newFolderName is the folder name with which you want to replace the folder1.

  • Related