views:

416

answers:

2

Hi guys, I'm writing a parser for some LISP files. I'm trying to get rid of leading whitespace in a string. The string contents are along the lines of:

         :FUNCTION (LAMBDA
                   (DELTA
                    PLASMA-IN-0)
                 (IF
                  (OR
                   (>=
                    #61=(+
                         (*
                          1
                          DELTA)
                         PLASMA-IN-0)
                    100)
                   (<=
                    #61#
                    0))
                  PLASMA-IN-0
                  #61#))

The tabs are all printed as 4 spaces in the file, so I want to get rid of these leading tabs.

I tried to do this: string.replaceAll("\\s{4}", " ") - but it had no effect at all on the string.

Does anyone know what I'm doing wrong? Is it because it is a multi-line string?

Thanks

+7  A: 
String.trim();

Should work.

denis
Thanks, that did work. Still not sure why the other one didn't though
waitinforatrain
+1  A: 

Your original regular expression didn't work because you forgot to escape the backslash. This should do what you were originally trying to do:

string.replaceAll("\\s{4}", " ")

EDIT: I didn't realize that you did not, in fact, forget to escape the backslash, and that Stack Overflow "ate" one of your backslashes, as Alan Moore pointed out in one of the comments to this answer (the only difference between "\s" and "\\s" is backticks around the text). That being said, my original answer isn't going to be of much help to you, so...

In order for this to be effective, you have to do something with the output from String#replaceAll, since it returns a new String instead of modifying the existing one (Strings are immutable, as William Brendel noted in his comment to your question).

string = string.replaceAll("\\s{4}", " ")

Since this answer didn't actually add anything of value, instead of deleting it, I'm making it Community Wiki.

Christopher Parker
He did write it that way, but he neglected to enclose that bit in backticks, so the site's formatting software ate one of the backslashes. (I just added the backticks, so it looks right now.) I suspect William Brendel got it right, and he just wasn't assigning the result of the `replaceAll` back to the variable.
Alan Moore
Ah. I didn't realize there was an issue with SO.
Christopher Parker
Test: \\s `\\s` \s `\s`
Christopher Parker
Odd. That issue is not present in comments.
Christopher Parker