Remove specific words in a string












7















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.










share|improve this question




















  • 2





    Consider mentioning the exact format of the date/time in the file name. That will help produce better solutions.

    – Sibgha
    Mar 21 at 10:52






  • 3





    Is it just the date you want to remove or all numbers?

    – Popeye
    Mar 21 at 10:55











  • Will extension always be .pdf?

    – Piro
    Mar 21 at 12:54











  • @Viper629 : Did any answer work for you? If yes do consider accepting/upvoting them. What should I do when someone answers my question?

    – Nicholas K
    Mar 22 at 7:12
















7















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.










share|improve this question




















  • 2





    Consider mentioning the exact format of the date/time in the file name. That will help produce better solutions.

    – Sibgha
    Mar 21 at 10:52






  • 3





    Is it just the date you want to remove or all numbers?

    – Popeye
    Mar 21 at 10:55











  • Will extension always be .pdf?

    – Piro
    Mar 21 at 12:54











  • @Viper629 : Did any answer work for you? If yes do consider accepting/upvoting them. What should I do when someone answers my question?

    – Nicholas K
    Mar 22 at 7:12














7












7








7


1






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.










share|improve this question
















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.







java string






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 21 at 11:29







Viper629

















asked Mar 21 at 10:44









Viper629Viper629

483




483








  • 2





    Consider mentioning the exact format of the date/time in the file name. That will help produce better solutions.

    – Sibgha
    Mar 21 at 10:52






  • 3





    Is it just the date you want to remove or all numbers?

    – Popeye
    Mar 21 at 10:55











  • Will extension always be .pdf?

    – Piro
    Mar 21 at 12:54











  • @Viper629 : Did any answer work for you? If yes do consider accepting/upvoting them. What should I do when someone answers my question?

    – Nicholas K
    Mar 22 at 7:12














  • 2





    Consider mentioning the exact format of the date/time in the file name. That will help produce better solutions.

    – Sibgha
    Mar 21 at 10:52






  • 3





    Is it just the date you want to remove or all numbers?

    – Popeye
    Mar 21 at 10:55











  • Will extension always be .pdf?

    – Piro
    Mar 21 at 12:54











  • @Viper629 : Did any answer work for you? If yes do consider accepting/upvoting them. What should I do when someone answers my question?

    – Nicholas K
    Mar 22 at 7:12








2




2





Consider mentioning the exact format of the date/time in the file name. That will help produce better solutions.

– Sibgha
Mar 21 at 10:52





Consider mentioning the exact format of the date/time in the file name. That will help produce better solutions.

– Sibgha
Mar 21 at 10:52




3




3





Is it just the date you want to remove or all numbers?

– Popeye
Mar 21 at 10:55





Is it just the date you want to remove or all numbers?

– Popeye
Mar 21 at 10:55













Will extension always be .pdf?

– Piro
Mar 21 at 12:54





Will extension always be .pdf?

– Piro
Mar 21 at 12:54













@Viper629 : Did any answer work for you? If yes do consider accepting/upvoting them. What should I do when someone answers my question?

– Nicholas K
Mar 22 at 7:12





@Viper629 : Did any answer work for you? If yes do consider accepting/upvoting them. What should I do when someone answers my question?

– Nicholas K
Mar 22 at 7:12












9 Answers
9






active

oldest

votes


















10














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}\.", "."));





share|improve this answer





















  • 1





    What if you did something like "test20190906.pdf".replaceAll("[0-9]{8}\.", ".") because if there is any reason a file may have a number at then end other than the date (ie JavaFinalYear5<date>.txt then you may want to preserve the number 5. This way you can just select the date, and no other numbers.

    – KGlasier
    Mar 21 at 20:39











  • @KGlasier : Yeah your suggestion was much better. Thanks.

    – Nicholas K
    Mar 22 at 6:46



















5














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"






share|improve this answer





















  • 1





    By reading the question we can suppose the format is filename+date+.pdf, if is not we have to search "2019" and remove it + next 4 characters but it will work only for 2019 dates and it will not work if filename contains "2019"

    – pavelbere
    Mar 21 at 11:04








  • 1





    Maybe we can or maybe not only , but it's less probably, my answer just approach the question based on my assumptions and maybe can help someone in that particular case

    – pavelbere
    Mar 21 at 11:10



















3














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.






share|improve this answer





















  • 2





    Should escape the dot too: "\d{8}\.pdf"

    – zwol
    Mar 21 at 13:18



















1














Assuming the date contains only numbers, you can use regex to replace numbers, e.g.:



String fileNameWithDate = "test20190906.pdf";
String fileName = fileNameWithDate.replaceAll("[0-9]+", ""));
System.out.println(fileName);





share|improve this answer





















  • 1





    he want to remove just a date, not all numbers

    – pavelbere
    Mar 21 at 10:51



















1














If the format of date is "yyyyMMdd" then I suggest go for the simplest solution as also given by @pavelbere. But this solution also assumes that the date always appends in the end of the filename.



String file = "test20190906.pdf"; 
String fileName = file.substring(0, file.length() - 12)+".pdf";





share|improve this answer
























  • But this solution also assumes that the date always appends in the end of the filename.

    – Sibgha
    Mar 21 at 11:05





















0














If you want to remove the dates only from the String then you can take a look on the solution (Assuming the date will come just before the .pdf) :



    String fileNameWithDate = "te3st320190906.pdf";

StringBuilder sb = new StringBuilder(fileNameWithDate).replace(fileNameWithDate.indexOf(".pdf") - 8,
fileNameWithDate.indexOf(".pdf"), "");
System.out.println(sb.toString());


Output:



te3st3.pdf





share|improve this answer


























  • What if the file name is test112019090611.pdf? Also, what is the point of all the StringBuilder etc... when you end up doing .replaceAll("[0-9]+", "") in the end?

    – Nicholas K
    Mar 21 at 10:59













  • Sorry I forgot to put that I have the assumption that date will come just before the .pdf .

    – Amit Bera
    Mar 21 at 11:01



















0














string name = "test20190906.pdf"
name.replaceAll("[0-9]","");





share|improve this answer































    0














    My approach would be to remove all numbers which are 8 digits long and are next to the last dot and replace them with a dot using the regex: (d{8})(?!.*d.).



    String filename = "filename12345678.pdf";
    filename = filename.replaceAll("(\d{8})(?!.*\d\.)\.", ".");


    You can see this being used and an explanation of what it does here.



    If the date can be different lengths then replace the {8} with a *, this enables the date to be any length.






    share|improve this answer

































      0














      An answer that doesn't use Regex:
      For filename as the original string:



      l = filename.split('.')
      l[-2] = l[-2][:-8]
      output = '.'.join(l)


      This uses the fact that the last '.' will always precede the extension, so the 8 characters prior to this will be dates. As long as we remove those, and put the '.' back in, we have the filename regardless of extension, regardless of characters preceding it, without using Regular Expressions.






      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55278652%2fremove-specific-words-in-a-string%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        9 Answers
        9






        active

        oldest

        votes








        9 Answers
        9






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        10














        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}\.", "."));





        share|improve this answer





















        • 1





          What if you did something like "test20190906.pdf".replaceAll("[0-9]{8}\.", ".") because if there is any reason a file may have a number at then end other than the date (ie JavaFinalYear5<date>.txt then you may want to preserve the number 5. This way you can just select the date, and no other numbers.

          – KGlasier
          Mar 21 at 20:39











        • @KGlasier : Yeah your suggestion was much better. Thanks.

          – Nicholas K
          Mar 22 at 6:46
















        10














        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}\.", "."));





        share|improve this answer





















        • 1





          What if you did something like "test20190906.pdf".replaceAll("[0-9]{8}\.", ".") because if there is any reason a file may have a number at then end other than the date (ie JavaFinalYear5<date>.txt then you may want to preserve the number 5. This way you can just select the date, and no other numbers.

          – KGlasier
          Mar 21 at 20:39











        • @KGlasier : Yeah your suggestion was much better. Thanks.

          – Nicholas K
          Mar 22 at 6:46














        10












        10








        10







        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}\.", "."));





        share|improve this answer















        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}\.", "."));






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 22 at 6:44

























        answered Mar 21 at 10:46









        Nicholas KNicholas K

        8,27661639




        8,27661639








        • 1





          What if you did something like "test20190906.pdf".replaceAll("[0-9]{8}\.", ".") because if there is any reason a file may have a number at then end other than the date (ie JavaFinalYear5<date>.txt then you may want to preserve the number 5. This way you can just select the date, and no other numbers.

          – KGlasier
          Mar 21 at 20:39











        • @KGlasier : Yeah your suggestion was much better. Thanks.

          – Nicholas K
          Mar 22 at 6:46














        • 1





          What if you did something like "test20190906.pdf".replaceAll("[0-9]{8}\.", ".") because if there is any reason a file may have a number at then end other than the date (ie JavaFinalYear5<date>.txt then you may want to preserve the number 5. This way you can just select the date, and no other numbers.

          – KGlasier
          Mar 21 at 20:39











        • @KGlasier : Yeah your suggestion was much better. Thanks.

          – Nicholas K
          Mar 22 at 6:46








        1




        1





        What if you did something like "test20190906.pdf".replaceAll("[0-9]{8}\.", ".") because if there is any reason a file may have a number at then end other than the date (ie JavaFinalYear5<date>.txt then you may want to preserve the number 5. This way you can just select the date, and no other numbers.

        – KGlasier
        Mar 21 at 20:39





        What if you did something like "test20190906.pdf".replaceAll("[0-9]{8}\.", ".") because if there is any reason a file may have a number at then end other than the date (ie JavaFinalYear5<date>.txt then you may want to preserve the number 5. This way you can just select the date, and no other numbers.

        – KGlasier
        Mar 21 at 20:39













        @KGlasier : Yeah your suggestion was much better. Thanks.

        – Nicholas K
        Mar 22 at 6:46





        @KGlasier : Yeah your suggestion was much better. Thanks.

        – Nicholas K
        Mar 22 at 6:46













        5














        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"






        share|improve this answer





















        • 1





          By reading the question we can suppose the format is filename+date+.pdf, if is not we have to search "2019" and remove it + next 4 characters but it will work only for 2019 dates and it will not work if filename contains "2019"

          – pavelbere
          Mar 21 at 11:04








        • 1





          Maybe we can or maybe not only , but it's less probably, my answer just approach the question based on my assumptions and maybe can help someone in that particular case

          – pavelbere
          Mar 21 at 11:10
















        5














        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"






        share|improve this answer





















        • 1





          By reading the question we can suppose the format is filename+date+.pdf, if is not we have to search "2019" and remove it + next 4 characters but it will work only for 2019 dates and it will not work if filename contains "2019"

          – pavelbere
          Mar 21 at 11:04








        • 1





          Maybe we can or maybe not only , but it's less probably, my answer just approach the question based on my assumptions and maybe can help someone in that particular case

          – pavelbere
          Mar 21 at 11:10














        5












        5








        5







        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"






        share|improve this answer















        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"







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 21 at 16:57

























        answered Mar 21 at 10:49









        pavelberepavelbere

        389110




        389110








        • 1





          By reading the question we can suppose the format is filename+date+.pdf, if is not we have to search "2019" and remove it + next 4 characters but it will work only for 2019 dates and it will not work if filename contains "2019"

          – pavelbere
          Mar 21 at 11:04








        • 1





          Maybe we can or maybe not only , but it's less probably, my answer just approach the question based on my assumptions and maybe can help someone in that particular case

          – pavelbere
          Mar 21 at 11:10














        • 1





          By reading the question we can suppose the format is filename+date+.pdf, if is not we have to search "2019" and remove it + next 4 characters but it will work only for 2019 dates and it will not work if filename contains "2019"

          – pavelbere
          Mar 21 at 11:04








        • 1





          Maybe we can or maybe not only , but it's less probably, my answer just approach the question based on my assumptions and maybe can help someone in that particular case

          – pavelbere
          Mar 21 at 11:10








        1




        1





        By reading the question we can suppose the format is filename+date+.pdf, if is not we have to search "2019" and remove it + next 4 characters but it will work only for 2019 dates and it will not work if filename contains "2019"

        – pavelbere
        Mar 21 at 11:04







        By reading the question we can suppose the format is filename+date+.pdf, if is not we have to search "2019" and remove it + next 4 characters but it will work only for 2019 dates and it will not work if filename contains "2019"

        – pavelbere
        Mar 21 at 11:04






        1




        1





        Maybe we can or maybe not only , but it's less probably, my answer just approach the question based on my assumptions and maybe can help someone in that particular case

        – pavelbere
        Mar 21 at 11:10





        Maybe we can or maybe not only , but it's less probably, my answer just approach the question based on my assumptions and maybe can help someone in that particular case

        – pavelbere
        Mar 21 at 11:10











        3














        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.






        share|improve this answer





















        • 2





          Should escape the dot too: "\d{8}\.pdf"

          – zwol
          Mar 21 at 13:18
















        3














        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.






        share|improve this answer





















        • 2





          Should escape the dot too: "\d{8}\.pdf"

          – zwol
          Mar 21 at 13:18














        3












        3








        3







        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.






        share|improve this answer















        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.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 22 at 3:21

























        answered Mar 21 at 10:57









        Mikhail IlinykhMikhail Ilinykh

        49329




        49329








        • 2





          Should escape the dot too: "\d{8}\.pdf"

          – zwol
          Mar 21 at 13:18














        • 2





          Should escape the dot too: "\d{8}\.pdf"

          – zwol
          Mar 21 at 13:18








        2




        2





        Should escape the dot too: "\d{8}\.pdf"

        – zwol
        Mar 21 at 13:18





        Should escape the dot too: "\d{8}\.pdf"

        – zwol
        Mar 21 at 13:18











        1














        Assuming the date contains only numbers, you can use regex to replace numbers, e.g.:



        String fileNameWithDate = "test20190906.pdf";
        String fileName = fileNameWithDate.replaceAll("[0-9]+", ""));
        System.out.println(fileName);





        share|improve this answer





















        • 1





          he want to remove just a date, not all numbers

          – pavelbere
          Mar 21 at 10:51
















        1














        Assuming the date contains only numbers, you can use regex to replace numbers, e.g.:



        String fileNameWithDate = "test20190906.pdf";
        String fileName = fileNameWithDate.replaceAll("[0-9]+", ""));
        System.out.println(fileName);





        share|improve this answer





















        • 1





          he want to remove just a date, not all numbers

          – pavelbere
          Mar 21 at 10:51














        1












        1








        1







        Assuming the date contains only numbers, you can use regex to replace numbers, e.g.:



        String fileNameWithDate = "test20190906.pdf";
        String fileName = fileNameWithDate.replaceAll("[0-9]+", ""));
        System.out.println(fileName);





        share|improve this answer















        Assuming the date contains only numbers, you can use regex to replace numbers, e.g.:



        String fileNameWithDate = "test20190906.pdf";
        String fileName = fileNameWithDate.replaceAll("[0-9]+", ""));
        System.out.println(fileName);






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 21 at 10:52

























        answered Mar 21 at 10:46









        Darshan MehtaDarshan Mehta

        23.4k32954




        23.4k32954








        • 1





          he want to remove just a date, not all numbers

          – pavelbere
          Mar 21 at 10:51














        • 1





          he want to remove just a date, not all numbers

          – pavelbere
          Mar 21 at 10:51








        1




        1





        he want to remove just a date, not all numbers

        – pavelbere
        Mar 21 at 10:51





        he want to remove just a date, not all numbers

        – pavelbere
        Mar 21 at 10:51











        1














        If the format of date is "yyyyMMdd" then I suggest go for the simplest solution as also given by @pavelbere. But this solution also assumes that the date always appends in the end of the filename.



        String file = "test20190906.pdf"; 
        String fileName = file.substring(0, file.length() - 12)+".pdf";





        share|improve this answer
























        • But this solution also assumes that the date always appends in the end of the filename.

          – Sibgha
          Mar 21 at 11:05


















        1














        If the format of date is "yyyyMMdd" then I suggest go for the simplest solution as also given by @pavelbere. But this solution also assumes that the date always appends in the end of the filename.



        String file = "test20190906.pdf"; 
        String fileName = file.substring(0, file.length() - 12)+".pdf";





        share|improve this answer
























        • But this solution also assumes that the date always appends in the end of the filename.

          – Sibgha
          Mar 21 at 11:05
















        1












        1








        1







        If the format of date is "yyyyMMdd" then I suggest go for the simplest solution as also given by @pavelbere. But this solution also assumes that the date always appends in the end of the filename.



        String file = "test20190906.pdf"; 
        String fileName = file.substring(0, file.length() - 12)+".pdf";





        share|improve this answer













        If the format of date is "yyyyMMdd" then I suggest go for the simplest solution as also given by @pavelbere. But this solution also assumes that the date always appends in the end of the filename.



        String file = "test20190906.pdf"; 
        String fileName = file.substring(0, file.length() - 12)+".pdf";






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 21 at 10:57









        SibghaSibgha

        1417




        1417













        • But this solution also assumes that the date always appends in the end of the filename.

          – Sibgha
          Mar 21 at 11:05





















        • But this solution also assumes that the date always appends in the end of the filename.

          – Sibgha
          Mar 21 at 11:05



















        But this solution also assumes that the date always appends in the end of the filename.

        – Sibgha
        Mar 21 at 11:05







        But this solution also assumes that the date always appends in the end of the filename.

        – Sibgha
        Mar 21 at 11:05













        0














        If you want to remove the dates only from the String then you can take a look on the solution (Assuming the date will come just before the .pdf) :



            String fileNameWithDate = "te3st320190906.pdf";

        StringBuilder sb = new StringBuilder(fileNameWithDate).replace(fileNameWithDate.indexOf(".pdf") - 8,
        fileNameWithDate.indexOf(".pdf"), "");
        System.out.println(sb.toString());


        Output:



        te3st3.pdf





        share|improve this answer


























        • What if the file name is test112019090611.pdf? Also, what is the point of all the StringBuilder etc... when you end up doing .replaceAll("[0-9]+", "") in the end?

          – Nicholas K
          Mar 21 at 10:59













        • Sorry I forgot to put that I have the assumption that date will come just before the .pdf .

          – Amit Bera
          Mar 21 at 11:01
















        0














        If you want to remove the dates only from the String then you can take a look on the solution (Assuming the date will come just before the .pdf) :



            String fileNameWithDate = "te3st320190906.pdf";

        StringBuilder sb = new StringBuilder(fileNameWithDate).replace(fileNameWithDate.indexOf(".pdf") - 8,
        fileNameWithDate.indexOf(".pdf"), "");
        System.out.println(sb.toString());


        Output:



        te3st3.pdf





        share|improve this answer


























        • What if the file name is test112019090611.pdf? Also, what is the point of all the StringBuilder etc... when you end up doing .replaceAll("[0-9]+", "") in the end?

          – Nicholas K
          Mar 21 at 10:59













        • Sorry I forgot to put that I have the assumption that date will come just before the .pdf .

          – Amit Bera
          Mar 21 at 11:01














        0












        0








        0







        If you want to remove the dates only from the String then you can take a look on the solution (Assuming the date will come just before the .pdf) :



            String fileNameWithDate = "te3st320190906.pdf";

        StringBuilder sb = new StringBuilder(fileNameWithDate).replace(fileNameWithDate.indexOf(".pdf") - 8,
        fileNameWithDate.indexOf(".pdf"), "");
        System.out.println(sb.toString());


        Output:



        te3st3.pdf





        share|improve this answer















        If you want to remove the dates only from the String then you can take a look on the solution (Assuming the date will come just before the .pdf) :



            String fileNameWithDate = "te3st320190906.pdf";

        StringBuilder sb = new StringBuilder(fileNameWithDate).replace(fileNameWithDate.indexOf(".pdf") - 8,
        fileNameWithDate.indexOf(".pdf"), "");
        System.out.println(sb.toString());


        Output:



        te3st3.pdf






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 21 at 11:02

























        answered Mar 21 at 10:54









        Amit BeraAmit Bera

        4,2261630




        4,2261630













        • What if the file name is test112019090611.pdf? Also, what is the point of all the StringBuilder etc... when you end up doing .replaceAll("[0-9]+", "") in the end?

          – Nicholas K
          Mar 21 at 10:59













        • Sorry I forgot to put that I have the assumption that date will come just before the .pdf .

          – Amit Bera
          Mar 21 at 11:01



















        • What if the file name is test112019090611.pdf? Also, what is the point of all the StringBuilder etc... when you end up doing .replaceAll("[0-9]+", "") in the end?

          – Nicholas K
          Mar 21 at 10:59













        • Sorry I forgot to put that I have the assumption that date will come just before the .pdf .

          – Amit Bera
          Mar 21 at 11:01

















        What if the file name is test112019090611.pdf? Also, what is the point of all the StringBuilder etc... when you end up doing .replaceAll("[0-9]+", "") in the end?

        – Nicholas K
        Mar 21 at 10:59







        What if the file name is test112019090611.pdf? Also, what is the point of all the StringBuilder etc... when you end up doing .replaceAll("[0-9]+", "") in the end?

        – Nicholas K
        Mar 21 at 10:59















        Sorry I forgot to put that I have the assumption that date will come just before the .pdf .

        – Amit Bera
        Mar 21 at 11:01





        Sorry I forgot to put that I have the assumption that date will come just before the .pdf .

        – Amit Bera
        Mar 21 at 11:01











        0














        string name = "test20190906.pdf"
        name.replaceAll("[0-9]","");





        share|improve this answer




























          0














          string name = "test20190906.pdf"
          name.replaceAll("[0-9]","");





          share|improve this answer


























            0












            0








            0







            string name = "test20190906.pdf"
            name.replaceAll("[0-9]","");





            share|improve this answer













            string name = "test20190906.pdf"
            name.replaceAll("[0-9]","");






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 21 at 11:13









            pamithapamitha

            3715




            3715























                0














                My approach would be to remove all numbers which are 8 digits long and are next to the last dot and replace them with a dot using the regex: (d{8})(?!.*d.).



                String filename = "filename12345678.pdf";
                filename = filename.replaceAll("(\d{8})(?!.*\d\.)\.", ".");


                You can see this being used and an explanation of what it does here.



                If the date can be different lengths then replace the {8} with a *, this enables the date to be any length.






                share|improve this answer






























                  0














                  My approach would be to remove all numbers which are 8 digits long and are next to the last dot and replace them with a dot using the regex: (d{8})(?!.*d.).



                  String filename = "filename12345678.pdf";
                  filename = filename.replaceAll("(\d{8})(?!.*\d\.)\.", ".");


                  You can see this being used and an explanation of what it does here.



                  If the date can be different lengths then replace the {8} with a *, this enables the date to be any length.






                  share|improve this answer




























                    0












                    0








                    0







                    My approach would be to remove all numbers which are 8 digits long and are next to the last dot and replace them with a dot using the regex: (d{8})(?!.*d.).



                    String filename = "filename12345678.pdf";
                    filename = filename.replaceAll("(\d{8})(?!.*\d\.)\.", ".");


                    You can see this being used and an explanation of what it does here.



                    If the date can be different lengths then replace the {8} with a *, this enables the date to be any length.






                    share|improve this answer















                    My approach would be to remove all numbers which are 8 digits long and are next to the last dot and replace them with a dot using the regex: (d{8})(?!.*d.).



                    String filename = "filename12345678.pdf";
                    filename = filename.replaceAll("(\d{8})(?!.*\d\.)\.", ".");


                    You can see this being used and an explanation of what it does here.



                    If the date can be different lengths then replace the {8} with a *, this enables the date to be any length.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Mar 21 at 11:44

























                    answered Mar 21 at 11:39









                    Toby SmithToby Smith

                    4181715




                    4181715























                        0














                        An answer that doesn't use Regex:
                        For filename as the original string:



                        l = filename.split('.')
                        l[-2] = l[-2][:-8]
                        output = '.'.join(l)


                        This uses the fact that the last '.' will always precede the extension, so the 8 characters prior to this will be dates. As long as we remove those, and put the '.' back in, we have the filename regardless of extension, regardless of characters preceding it, without using Regular Expressions.






                        share|improve this answer




























                          0














                          An answer that doesn't use Regex:
                          For filename as the original string:



                          l = filename.split('.')
                          l[-2] = l[-2][:-8]
                          output = '.'.join(l)


                          This uses the fact that the last '.' will always precede the extension, so the 8 characters prior to this will be dates. As long as we remove those, and put the '.' back in, we have the filename regardless of extension, regardless of characters preceding it, without using Regular Expressions.






                          share|improve this answer


























                            0












                            0








                            0







                            An answer that doesn't use Regex:
                            For filename as the original string:



                            l = filename.split('.')
                            l[-2] = l[-2][:-8]
                            output = '.'.join(l)


                            This uses the fact that the last '.' will always precede the extension, so the 8 characters prior to this will be dates. As long as we remove those, and put the '.' back in, we have the filename regardless of extension, regardless of characters preceding it, without using Regular Expressions.






                            share|improve this answer













                            An answer that doesn't use Regex:
                            For filename as the original string:



                            l = filename.split('.')
                            l[-2] = l[-2][:-8]
                            output = '.'.join(l)


                            This uses the fact that the last '.' will always precede the extension, so the 8 characters prior to this will be dates. As long as we remove those, and put the '.' back in, we have the filename regardless of extension, regardless of characters preceding it, without using Regular Expressions.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 21 at 15:24









                            Jim EisenbergJim Eisenberg

                            10716




                            10716






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55278652%2fremove-specific-words-in-a-string%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Masuk log Menu navigasi

                                Identifying “long and narrow” polygons in with PostGISlength and width of polygonWhy postgis st_overlaps reports Qgis' “avoid intersections” generated polygon as overlapping with others?Adjusting polygons to boundary and filling holesDrawing polygons with fixed area?How to remove spikes in Polygons with PostGISDeleting sliver polygons after difference operation in QGIS?Snapping boundaries in PostGISSplit polygon into parts adding attributes based on underlying polygon in QGISSplitting overlap between polygons and assign to nearest polygon using PostGIS?Expanding polygons and clipping at midpoint?Removing Intersection of Buffers in Same Layers

                                Старые Смолеговицы Содержание История | География | Демография | Достопримечательности | Примечания | НавигацияHGЯOLHGЯOL41 206 832 01641 606 406 141Административно-территориальное деление Ленинградской области«Переписная оброчная книга Водской пятины 1500 года», С. 793«Карта Ингерманландии: Ивангорода, Яма, Копорья, Нотеборга», по материалам 1676 г.«Генеральная карта провинции Ингерманландии» Э. Белинга и А. Андерсина, 1704 г., составлена по материалам 1678 г.«Географический чертёж над Ижорскою землей со своими городами» Адриана Шонбека 1705 г.Новая и достоверная всей Ингерманландии ланткарта. Грав. А. Ростовцев. СПб., 1727 г.Топографическая карта Санкт-Петербургской губернии. 5-и верстка. Шуберт. 1834 г.Описание Санкт-Петербургской губернии по уездам и станамСпецкарта западной части России Ф. Ф. Шуберта. 1844 г.Алфавитный список селений по уездам и станам С.-Петербургской губернииСписки населённых мест Российской Империи, составленные и издаваемые центральным статистическим комитетом министерства внутренних дел. XXXVII. Санкт-Петербургская губерния. По состоянию на 1862 год. СПб. 1864. С. 203Материалы по статистике народного хозяйства в С.-Петербургской губернии. Вып. IX. Частновладельческое хозяйство в Ямбургском уезде. СПб, 1888, С. 146, С. 2, 7, 54Положение о гербе муниципального образования Курское сельское поселениеСправочник истории административно-территориального деления Ленинградской области.Топографическая карта Ленинградской области, квадрат О-35-23-В (Хотыницы), 1930 г.АрхивированоАдминистративно-территориальное деление Ленинградской области. — Л., 1933, С. 27, 198АрхивированоАдминистративно-экономический справочник по Ленинградской области. — Л., 1936, с. 219АрхивированоАдминистративно-территориальное деление Ленинградской области. — Л., 1966, с. 175АрхивированоАдминистративно-территориальное деление Ленинградской области. — Лениздат, 1973, С. 180АрхивированоАдминистративно-территориальное деление Ленинградской области. — Лениздат, 1990, ISBN 5-289-00612-5, С. 38АрхивированоАдминистративно-территориальное деление Ленинградской области. — СПб., 2007, с. 60АрхивированоКоряков Юрий База данных «Этно-языковой состав населённых пунктов России». Ленинградская область.Административно-территориальное деление Ленинградской области. — СПб, 1997, ISBN 5-86153-055-6, С. 41АрхивированоКультовый комплекс Старые Смолеговицы // Электронная энциклопедия ЭрмитажаПроблемы выявления, изучения и сохранения культовых комплексов с каменными крестами: по материалам работ 2016-2017 гг. в Ленинградской области