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+$", "");
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();
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.