我需要删除网址末尾的所有内容,并且我不知道最后有多少斜线。
例如
http://www.example.com/user//
在最后删除slashe后
http://www.example.com/user
有没有像正则表达这样的简单方法。
答案 0 :(得分:4)
使用String.replaceAll ("\\/$", "");
$
表示它位于字符串
根据@WiktorStribiżew删除多个斜杠
使用String.replaceAll ("/+$", "");
答案 1 :(得分:0)
有两种方法:使用模式匹配(稍慢):
s = s.replaceAll("/$", "");
或url.replaceFirst("/*$", "");
或
s = s.replaceAll("/\\z", "");
并使用if语句(稍快):
if (s.endsWith("/")) {
s = s.substring(0, s.length() - 1);
}
或有点难看:
s = s.substring(0, s.length() - (s.endsWith("/") ? 1 : 0));
请注意你需要使用s = s,因为字符串是不可变的。