Search code examples
javajava-6

Remove some text between square brackets in Java 6


Would it be possible to change this:

[quote]user1 posted:
      [quote]user2 posted:
              Test1
      [/quote]
      Test2
[/quote]
Test3

to this:

Test3

Using Java 6?


Solution

  • I compiled this to Java 8. I don't believe I'm using any features not available in Java 6.

    Edited: System.lineSeparator() was added in Java 1.7. I changed the line to System.getProperty("line.separator").

    public class RemoveQuotes {
    
        public static void main(String[] args) {
            String input = "[quote]user1 posted:\r\n" + 
                    "      [quote]user2 posted:\r\n" + 
                    "              Test1\r\n" + 
                    "      [/quote]\r\n" + 
                    "      Test2\r\n" + 
                    "[/quote]\r\n" + 
                    "Test3";
            
            input = input.replace(System.getProperty("line.separator"), "");
            String endQuote = "[/quote]";
            int endPosition;
            
            do {
                int startPosition = input.indexOf("[quote]");
                endPosition = input.lastIndexOf(endQuote);
                if (endPosition >= 0) {
                    String output = input.substring(0, startPosition);
                    output += input.substring(endPosition + endQuote.length());
                    input = output;
                }
            } while (endPosition >= 0);
            
            System.out.println(input);
        }
    
    }