Given a string = "test20190906.pdf", how can I get only "test.pdf" such that it removes the date from the string by using string.replace or remove ?
Considering the format will always be filename + date + .extension.
Given a String and a Word, the task is remove that Word from the String. Approach : In Java, this can be done using String replaceAll method by replacing given word with a blank space. string string1 = "Geeks for Geeks.";
Iterate the array and check the word not equal to the given word. Concatenate the word into a new string array name as a new string. Print the new string. This method takes two input old_word and the new word in the regex format. Replace all the old_word with the new word.
We can remove part of the string using REPLACE () function. We can use this function if we know the exact character of the string to remove. REMOVE (): This function replaces all occurrences of a substring within a new substring.
Approach : In Java, this can be done using String replaceAll method by replacing given word with a blank space. string string1 = "Geeks for Geeks."; string string2 = "for Geeks Geeks."; string string3 = "Geeks Geeks for."; string string4 = "A computer Science Portal.";
You can use a regex to remove consecutive digits that resemble a date in any format provided the filename is appended immediately by the date.
"test20190906.pdf".replaceAll("[0-9]{8}\\.", "."));
There are a lot of good answers, but I want present one more. It'll work if filename contains digits not only in date part. I assume that date is always appears before extension and has fixed length.
s.replaceAll("\\d{8}\\.pdf", ".pdf");
And if the file extension varies then you could do some additional work:
public static String removeDate(String s) {
final String extension = s.substring(s.lastIndexOf("."));
final String pattern = "\\d{8}\\" + extension;
return s.replaceAll(pattern, extension);
}
public static void main(String args[])
{
System.out.println(removeDate("test20190101.pdf"));
System.out.println(removeDate("123123test20190101.txt"));
System.out.println(removeDate("123te11st20190101.csv"));
}
This can be done with the regexp only, but at the cost of readability.
I see previous answers and that answers does not work if you got other numbers in file name for example: 01_test20190913.pdf
In that case solution will be
String file = "01_test20190913.pdf";
System.out.println(file.substring(0, file.length() - 12)+".pdf");
here i take the first part of string without last 12 characters and add ".pdf"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With