Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String extraction/manipulation in Java

Tags:

java

string

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://someurl/search.do?"

Is there a String operation in Java to achieve the above action ?

Thanks, Sony

like image 926
sony Avatar asked May 08 '26 22:05

sony


2 Answers

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.

like image 163
Lukas Eder Avatar answered May 10 '26 12:05

Lukas Eder


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.

like image 31
trojanfoe Avatar answered May 10 '26 12:05

trojanfoe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!