String extraction/manipulation in Java
String url = "http://someurl/search.do?/remainingurl"
I would like to scrape the above string from the first character upto search.do?
Meaning, the resulting String would look like so:
String scrapedUrl = "http://someu开发者_运维百科rl/search.do?"
Is there a String operation in Java to achieve the above action ?
Thanks, Sony
Use a regular expression:
String scrapedUrl = url.replaceAll("(.*?search\\.do\\?).*", "$1");
Of course you can use indexOf
solutions and all of that, but your requirement was to exactly ''match'' everything up until the first search.do?
. That kind of operation is best done using a regular expression.
Try this (untested):
int index = url.indexOf("?");
if (index >= 0)
url= url.substring(0, index);
It looks for the first occurance of the '?' character and if found chops off the characters that follow.
You can use a combination of indexOf() and subString() to chop up the String. Check out the methods of String in the API:
http://download.oracle.com/javase/6/docs/api/java/lang/String.html
Yes, use this : subString(start, end)
and indexOf(string)
I would recommend:
int index = url.indexOf("?");
String newURL = url.subString(0,index);
You can use substring and indexOf
String scrapedUrl = url.substring(0, url.indexOf('?');
final String splitter = "search.do?";
String[] strings = url.split("search\\.do\\?");
String scrapedUrl = strings[0] + splitter;
Read more.
String url = "http://someurl/search.do?/remainingurl";
String scrapedUrl =url.substring(0,url.lastIndexOf("?")+1);
System.out.println(scrapedUrl);
精彩评论