在java中删除url末尾的所有斜杠的简单方法

时间:2016-09-27 06:15:23

标签: java string

我需要删除网址末尾的所有内容,并且我不知道最后有多少斜线。

例如

http://www.example.com/user//

在最后删除slashe后

http://www.example.com/user

有没有像正则表达这样的简单方法。

2 个答案:

答案 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,因为字符串是不可变的。