Results 1 to 3 of 3
  1. #1
    TheNadz is offline Member
    Join Date
    Nov 2010
    Posts
    9
    Rep Power
    0

    Default String.replaceAll(str, str) is leading to infinite loop. Help?

    The String variable body is assigned a value by the user and then this code should be replacing any number of carriage returns with a single string "<*>".

    If I run just the first replaceAll() then it works fine. If I run either of the codes blow then the program stalls.

    Java Code:
    body = body.replaceAll("\n", "<*>");
    Java Code:
    body = body.replaceAll("<*><*>", "<*>");
    I also tried a while loop

    Java Code:
    while(body.indexOf("<*><*>") != -1)
    body.replaceNext("<*><*>", "<*>");
    Like I said, they all ended in a stalled program.

    Any help would be greatly appreciated!

    Here is a compilable test code:

    Java Code:
    public class Test {
    
    	public static void main(String[] args){
    		String body = "This is a \n\n test of a code I would like\n\n to work.. \nbut\n\n it is not working.\n";
    		System.err.println(body);
    		
    		body = body.replaceAll("\n", "<*>");
    		System.err.println(body);
    		
    		body = body.replaceAll("<*><*>", "<*>");
    		System.err.println(body);
    	}
    }
    For some reason it is not stalling in this but it is also not replacing anything. Thoughts?

  2. #2
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    6

    Default

    The first argument is a regex, and * is a special regex character (zero or more times) so you have to escape it -> Geek And Poke: The Geek Joke Of The Week :D

    Try body = body.replaceAll("<\\*><\\*>", "<*>");

    edit: or change your first replace statement --> body = body.replaceAll("\n+", "<*>");
    Last edited by eRaaaa; 04-25-2011 at 04:11 PM.

  3. #3
    TheNadz is offline Member
    Join Date
    Nov 2010
    Posts
    9
    Rep Power
    0

    Default

    Thanks so much! Makes complete sense now that you say it.

    edit: And the comic is fantastic! LOL!

Similar Threads

  1. infinite loop
    By javapink in forum New To Java
    Replies: 19
    Last Post: 03-06-2011, 02:28 AM
  2. Regular Expressions and String.replaceAll()
    By meta1203 in forum New To Java
    Replies: 1
    Last Post: 11-24-2010, 11:41 PM
  3. how to end infinite loop
    By search4survival in forum New To Java
    Replies: 14
    Last Post: 10-25-2010, 08:59 AM
  4. Infinite loop
    By jDennis79 in forum New To Java
    Replies: 7
    Last Post: 08-13-2010, 11:45 PM
  5. Infinite Loop
    By bosoxfan in forum New To Java
    Replies: 3
    Last Post: 02-22-2010, 01:34 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •