Paul
Paul

Reputation: 970

Java regex to remove newline and space at the end of string

I'm new to java regex so this question might be easy for someone. I have a raw string:

"\n\n This is \n\r simple \n     string \r   "

Now I want to format it to:

"This is \n\r simple \n    string"

I want to trim this tring at the start and end of this string. But the trim() method works only with the white space (\s).

I try to use replace first

replaceFirst("[\\t\\n\\r]", "") 

and it works fine with the start of the string. But dont see the replace last, so I use

replaceAll("[\\t\\n\\r]$", "\n")

The "$" will affect only the last one, but in case of "\r\r\n\n", only the last \n replaced.

How can I remove all the "\r\r\n\n" at the last of the string?

Thanks

UPDATE:

Sorry, Im lazy not to test carefully. trim() works fine in this case.

Upvotes: 0

Views: 1876

Answers (2)

hwnd
hwnd

Reputation: 70722

You don't need a regex for this, trim() will do the job.

String result = oldstring.trim();

Ideone Demo

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

If you are set on using regular expressions*, you can do it this way:

s = s.replaceAll("^\\s+|\\s+$", "");

Demo.

The expression removes a sequence of spaces at the beginning (i.e. after an ^ anchor) or at the end (i.e. before the $ anchor).

* Presumably, you may want to do it only as a learning exercise, because trim() method does exactly the same thing.

Upvotes: 1

Related Questions