Reputation: 970
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
Reputation: 70722
You don't need a regex for this, trim()
will do the job.
String result = oldstring.trim();
Upvotes: 1
Reputation: 726489
If you are set on using regular expressions*, you can do it this way:
s = s.replaceAll("^\\s+|\\s+$", "");
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