Troubleshooting Java replaceAll












0















I am trying to write a method that accepts an input string to be found and an input string to replace all instances of the found word and to return the number of replacements made. I am trying to use pattern and matcher from JAVA regex. I have a text file called "text.txt" which includes "this is a test this is a test this is a test". When I try to search for "test" and replace it with "mess", the method returns 1 each time and none of the words test are replaced.



public int findAndRepV2(String word, String replace) throws FileNotFoundException, IOException 
{
int cnt = 0;

BufferedReader input = new BufferedReader( new FileReader(this.filename));
Writer fw = new FileWriter("test.txt");
String line = input.readLine();


while (line != null)
{
Pattern pattern = Pattern.compile(word, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {matcher.replaceAll(replace); cnt++;}

line = input.readLine();
}
fw.close();
return cnt;
}









share|improve this question


















  • 1





    Possible duplicate of Find and replace words/lines in a file

    – Centos
    Nov 26 '18 at 13:20











  • You want to replace a literal string. Why would you use a regex? Also, replaceAll doesn't return the number of replacements, so how could it work?

    – JB Nizet
    Nov 26 '18 at 13:21
















0















I am trying to write a method that accepts an input string to be found and an input string to replace all instances of the found word and to return the number of replacements made. I am trying to use pattern and matcher from JAVA regex. I have a text file called "text.txt" which includes "this is a test this is a test this is a test". When I try to search for "test" and replace it with "mess", the method returns 1 each time and none of the words test are replaced.



public int findAndRepV2(String word, String replace) throws FileNotFoundException, IOException 
{
int cnt = 0;

BufferedReader input = new BufferedReader( new FileReader(this.filename));
Writer fw = new FileWriter("test.txt");
String line = input.readLine();


while (line != null)
{
Pattern pattern = Pattern.compile(word, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {matcher.replaceAll(replace); cnt++;}

line = input.readLine();
}
fw.close();
return cnt;
}









share|improve this question


















  • 1





    Possible duplicate of Find and replace words/lines in a file

    – Centos
    Nov 26 '18 at 13:20











  • You want to replace a literal string. Why would you use a regex? Also, replaceAll doesn't return the number of replacements, so how could it work?

    – JB Nizet
    Nov 26 '18 at 13:21














0












0








0








I am trying to write a method that accepts an input string to be found and an input string to replace all instances of the found word and to return the number of replacements made. I am trying to use pattern and matcher from JAVA regex. I have a text file called "text.txt" which includes "this is a test this is a test this is a test". When I try to search for "test" and replace it with "mess", the method returns 1 each time and none of the words test are replaced.



public int findAndRepV2(String word, String replace) throws FileNotFoundException, IOException 
{
int cnt = 0;

BufferedReader input = new BufferedReader( new FileReader(this.filename));
Writer fw = new FileWriter("test.txt");
String line = input.readLine();


while (line != null)
{
Pattern pattern = Pattern.compile(word, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {matcher.replaceAll(replace); cnt++;}

line = input.readLine();
}
fw.close();
return cnt;
}









share|improve this question














I am trying to write a method that accepts an input string to be found and an input string to replace all instances of the found word and to return the number of replacements made. I am trying to use pattern and matcher from JAVA regex. I have a text file called "text.txt" which includes "this is a test this is a test this is a test". When I try to search for "test" and replace it with "mess", the method returns 1 each time and none of the words test are replaced.



public int findAndRepV2(String word, String replace) throws FileNotFoundException, IOException 
{
int cnt = 0;

BufferedReader input = new BufferedReader( new FileReader(this.filename));
Writer fw = new FileWriter("test.txt");
String line = input.readLine();


while (line != null)
{
Pattern pattern = Pattern.compile(word, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {matcher.replaceAll(replace); cnt++;}

line = input.readLine();
}
fw.close();
return cnt;
}






java regex replaceall






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 26 '18 at 13:15









TacoB2018TacoB2018

183




183








  • 1





    Possible duplicate of Find and replace words/lines in a file

    – Centos
    Nov 26 '18 at 13:20











  • You want to replace a literal string. Why would you use a regex? Also, replaceAll doesn't return the number of replacements, so how could it work?

    – JB Nizet
    Nov 26 '18 at 13:21














  • 1





    Possible duplicate of Find and replace words/lines in a file

    – Centos
    Nov 26 '18 at 13:20











  • You want to replace a literal string. Why would you use a regex? Also, replaceAll doesn't return the number of replacements, so how could it work?

    – JB Nizet
    Nov 26 '18 at 13:21








1




1





Possible duplicate of Find and replace words/lines in a file

– Centos
Nov 26 '18 at 13:20





Possible duplicate of Find and replace words/lines in a file

– Centos
Nov 26 '18 at 13:20













You want to replace a literal string. Why would you use a regex? Also, replaceAll doesn't return the number of replacements, so how could it work?

– JB Nizet
Nov 26 '18 at 13:21





You want to replace a literal string. Why would you use a regex? Also, replaceAll doesn't return the number of replacements, so how could it work?

– JB Nizet
Nov 26 '18 at 13:21












1 Answer
1






active

oldest

votes


















0














First, you need to ensure that the text you are searching for is not interpreted as a regex. You should do:



Pattern pattern = Pattern.compile(Pattern.quote(word), Pattern.CASE_INSENSITIVE);


Second, replaceAll does something like this:



public String replaceAll(String replacement) {
reset();
boolean result = find();
if (result) {
StringBuffer sb = new StringBuffer();
do {
appendReplacement(sb, replacement);
result = find();
} while (result);
appendTail(sb);
return sb.toString();
}
return text.toString();
}


Note how it calls find until it can't find anything. This means that your loop will only be run once, since after the first call to replaceAll, the matcher has already found everything.



You should use appendReplacement instead:



StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buffer, replace);
cnt++;
}
buffer.append(line.substring(matcher.end()));
// "buffer" contains the string after the replacement


I noticed that in your method, you didn't actually do anything with the string after the replacement. If that's the case, just count how many times find returns true:



while (matcher.find()) {
cnt++;
}





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%2f53481941%2ftroubleshooting-java-replaceall%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    First, you need to ensure that the text you are searching for is not interpreted as a regex. You should do:



    Pattern pattern = Pattern.compile(Pattern.quote(word), Pattern.CASE_INSENSITIVE);


    Second, replaceAll does something like this:



    public String replaceAll(String replacement) {
    reset();
    boolean result = find();
    if (result) {
    StringBuffer sb = new StringBuffer();
    do {
    appendReplacement(sb, replacement);
    result = find();
    } while (result);
    appendTail(sb);
    return sb.toString();
    }
    return text.toString();
    }


    Note how it calls find until it can't find anything. This means that your loop will only be run once, since after the first call to replaceAll, the matcher has already found everything.



    You should use appendReplacement instead:



    StringBuffer buffer = new StringBuffer();
    while (matcher.find()) {
    matcher.appendReplacement(buffer, replace);
    cnt++;
    }
    buffer.append(line.substring(matcher.end()));
    // "buffer" contains the string after the replacement


    I noticed that in your method, you didn't actually do anything with the string after the replacement. If that's the case, just count how many times find returns true:



    while (matcher.find()) {
    cnt++;
    }





    share|improve this answer




























      0














      First, you need to ensure that the text you are searching for is not interpreted as a regex. You should do:



      Pattern pattern = Pattern.compile(Pattern.quote(word), Pattern.CASE_INSENSITIVE);


      Second, replaceAll does something like this:



      public String replaceAll(String replacement) {
      reset();
      boolean result = find();
      if (result) {
      StringBuffer sb = new StringBuffer();
      do {
      appendReplacement(sb, replacement);
      result = find();
      } while (result);
      appendTail(sb);
      return sb.toString();
      }
      return text.toString();
      }


      Note how it calls find until it can't find anything. This means that your loop will only be run once, since after the first call to replaceAll, the matcher has already found everything.



      You should use appendReplacement instead:



      StringBuffer buffer = new StringBuffer();
      while (matcher.find()) {
      matcher.appendReplacement(buffer, replace);
      cnt++;
      }
      buffer.append(line.substring(matcher.end()));
      // "buffer" contains the string after the replacement


      I noticed that in your method, you didn't actually do anything with the string after the replacement. If that's the case, just count how many times find returns true:



      while (matcher.find()) {
      cnt++;
      }





      share|improve this answer


























        0












        0








        0







        First, you need to ensure that the text you are searching for is not interpreted as a regex. You should do:



        Pattern pattern = Pattern.compile(Pattern.quote(word), Pattern.CASE_INSENSITIVE);


        Second, replaceAll does something like this:



        public String replaceAll(String replacement) {
        reset();
        boolean result = find();
        if (result) {
        StringBuffer sb = new StringBuffer();
        do {
        appendReplacement(sb, replacement);
        result = find();
        } while (result);
        appendTail(sb);
        return sb.toString();
        }
        return text.toString();
        }


        Note how it calls find until it can't find anything. This means that your loop will only be run once, since after the first call to replaceAll, the matcher has already found everything.



        You should use appendReplacement instead:



        StringBuffer buffer = new StringBuffer();
        while (matcher.find()) {
        matcher.appendReplacement(buffer, replace);
        cnt++;
        }
        buffer.append(line.substring(matcher.end()));
        // "buffer" contains the string after the replacement


        I noticed that in your method, you didn't actually do anything with the string after the replacement. If that's the case, just count how many times find returns true:



        while (matcher.find()) {
        cnt++;
        }





        share|improve this answer













        First, you need to ensure that the text you are searching for is not interpreted as a regex. You should do:



        Pattern pattern = Pattern.compile(Pattern.quote(word), Pattern.CASE_INSENSITIVE);


        Second, replaceAll does something like this:



        public String replaceAll(String replacement) {
        reset();
        boolean result = find();
        if (result) {
        StringBuffer sb = new StringBuffer();
        do {
        appendReplacement(sb, replacement);
        result = find();
        } while (result);
        appendTail(sb);
        return sb.toString();
        }
        return text.toString();
        }


        Note how it calls find until it can't find anything. This means that your loop will only be run once, since after the first call to replaceAll, the matcher has already found everything.



        You should use appendReplacement instead:



        StringBuffer buffer = new StringBuffer();
        while (matcher.find()) {
        matcher.appendReplacement(buffer, replace);
        cnt++;
        }
        buffer.append(line.substring(matcher.end()));
        // "buffer" contains the string after the replacement


        I noticed that in your method, you didn't actually do anything with the string after the replacement. If that's the case, just count how many times find returns true:



        while (matcher.find()) {
        cnt++;
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 26 '18 at 13:42









        SweeperSweeper

        71.5k1075144




        71.5k1075144
































            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%2f53481941%2ftroubleshooting-java-replaceall%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

            Costa Masnaga

            Create new schema in PostgreSQL using DBeaver

            Fotorealismo