简体   繁体   中英

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.

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 (ie after an ^ anchor) or at the end (ie before the $ anchor).

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

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

String result = oldstring.trim();

Ideone Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM