For example, I have a string a="\\\\a\\\\b\\\\";
How to remove all escape slashes in leading and trailing for it, so the processed string will be a\\\\b
.
I tried using:
a=a.replaceFirst("\\+$", "");
a=a.replaceFirst("\\+", "");
But it's not working correctly as I expected.
You can just use two regexes:
String a = "\\\\a\\b\\\\\\";
System.out.println(
a.replaceAll("^\\\\+", "")
.replaceAll("\\\\+$", "")
);
So many bars, right? This is because to express a single "\\"
in a String, we need to scape it with another bar, which will be "\\\\"
. But, \\
is also a special char for regular expressions, so you need to scape it too.
That is why you need four \\\\\\\\
, which will be "translated" to just two.
Loop through the String from start until you hit a non slash and remove slashes before it and vice versa for trailing.
I wouldn't use a regex for something this trivial.
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.