7 Replies Latest reply on Dec 3, 2012 1:52 PM by 955926

    String replace method

      Hi all

      Im writing a simple post ocr correction program and have come across something I dont understand

      Look at the method below - simply replace one string with another (works ok mostly but unsure on replacing text with non Letter chars)

      public String replaceGroup(String in){          
      String word = in;
                word = in.replace("\"IT", "TT");// "IT not working
                word = in.replace("'I'l'", "TT");// "I'l' not working
                word = in.replace("'I'I'", "TT");// 'I'I'
                return word;

      Its not a big problem but I curious whats going on here - im assuming this is something to do with escape characters. I cant understand why the last one works but the first 2 dont

      Just a bit confused as of why. Im not looking for a way to resolve this as i could just write my own replace method: i just want to know why its not working like this

        • 1. Re: String replace method
          You need four backslashes: two for the Java compiler and two more for the regex. So, "\\\\"IT".
          • 2. Re: String replace method
            it wont compile with 4 \: the compiler treats it as esc, \(char), esc, \(char), "(end of string), IT

            thanks for the quick reply
            • 3. Re: String replace method
              So did you try three? Or are you just waiting here, maybe forever?
              • 4. Re: String replace method
                Tried all numbers 1-9 none work, the ones that compile run but dont replace string. Besides that doesnt explain why *'I'I'* isnt being replaced

                Edited by: 952923 on Dec 3, 2012 1:49 AM

                Edited by: 952923 on Dec 3, 2012 1:50 AM
                • 5. Re: String replace method
                  EJP wrote:
                  You need four backslashes: two for the Java compiler and two more for the regex. So, "\\\\"IT".
                  (regex? Its replace(), not replaceAll())
                  • 6. Re: String replace method
                    952923 wrote:
                              word = in.replace("\"IT", "TT");// "IT not working
                    You should rather state not compilable ...

                    Then your Patterns work great:
                        public final void testEscapes() {
                            Assert.assertEquals("\"IT -> XX", "XX", "\"IT".replaceAll("\"IT", "XX"));
                            Assert.assertEquals("I'I' -> XX", "XX", "I'I'".replaceAll("I'I'", "XX"));
                            Assert.assertEquals("'I'I' -> XX", "XX", "'I'I'".replaceAll("'I'I'", "XX"));
                    • 7. Re: String replace method
                      Cheers thats what i was looking for. I never have much luck with the replace method.