Removing spaces in a Java string?

I am writing a parser for some LISP files. I am trying to get rid of leading spaces in a string. The contents of the line correspond to the lines:

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

All tabs are 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 this did not affect the line in any way.

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

thanks

+4
source share
2 answers
 String.trim(); 

Must work.

+8
source

Your original regex does not work because you forgot to escape the backslash. This should do what you originally tried to do:

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

EDIT : I didn’t understand that you really didn’t do this, forgetting to avoid the backslash, and that Qaru “ate” one of your backslashes, as Alan Moore indicated in one of the comments to this answer (the only difference between "\ s" and " \\s " are backlinks around the text). However, my initial answer will not be very useful to you, so ...

For this to be effective, you need to do something with the output of String # replaceAll , as it returns a new string instead of changing the existing one ( Strings are unchangeable , as William Brendel noted in his comment on your question).

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

Since this answer did not actually add anything useful, instead of deleting it, I am making it a Community Wiki.

+1
source

Source: https://habr.com/ru/post/1302697/


All Articles