[英]Need to Trim Java String
I need help in trimming a string url. 我需要帮助修剪字符串网址。
Let's say the String is http://myurl.com/users/232222232/pageid
假设字符串是
http://myurl.com/users/232222232/pageid
What i would like returned would be /232222232/pageid
我想要的是
/232222232/pageid
Now the 'myurl.com' can change but the /users/
will always be the same. 现在'myurl.com'可以改变,但
/users/
将始终是相同的。
I suggest you use substring
and indexOf("/users/")
. 我建议你使用
substring
和indexOf("/users/")
。
String url = "http://myurl.com/users/232222232/pageid";
String lastPart = url.substring(url.indexOf("/users/") + 6);
System.out.println(lastPart); // prints "/232222232/pageid"
A slightly more sophisticated variant would be to let the URL
class parse the url for you: 一个稍微复杂的变体是让
URL
类为你解析url:
URL url = new URL("http://myurl.com/users/232222232/pageid");
String lastPart = url.getPath().substring(6);
System.out.println(lastPart); // prints "/232222232/pageid"
And, a third approach, using regular expressions: 第三种方法,使用正则表达式:
String url = "http://myurl.com/users/232222232/pageid";
String lastPart = url.replaceAll(".*/users", "");
System.out.println(lastPart); // prints "/232222232/pageid"
String rest = url.substring(url.indexOf("/users/") + 6);
string.replaceAll(".*/users(/.*/.*)", "$1");
You can use split(String regex,int limit)
which will split the string around the pattern in regex
at most limit
times, so... 您可以使用
split(String regex,int limit)
,它将在regex
中围绕模式分割字符串最多limit
时间,因此......
String url="http://myurl.com/users/232222232/pageid";
String[] parts=url.split("/users",1);
//parts={"http://myurl.com","/232222232/pageid"}
String rest=parts[1];
//rest="/232222232/pageid"
The limit is there to prevent strings like "http://myurl.com/users/232222232/users/pageid"
giving answers like "/232222232"
. 限制是为了防止像
"http://myurl.com/users/232222232/users/pageid"
这样的字符串给出答案,如"/232222232"
。
You can use String.indexOf()
and String.substring()
in order to achieve this: 您可以使用
String.indexOf()
和String.substring()
来实现此目的:
String pattern = "/users/";
String url = "http://myurl.com/users/232222232/pageid";
System.out.println(url.substring(url.indexOf(pattern)+pattern.length()-1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.