Replace multiple substrings within a string - java

I have string such as
String url = "www.test.com/blabla/?p1=v1?p2=v2?p3=v3"
I would like to replace the "substrings" "v1","v2" and "v3" with other values. How can I achieve this?

Does something like this work for your case?
String url = "www.test.com/blabla/?p1=v1?p2=v2?p3=v3";
String result = String.format(url.replaceAll("v[0-9]", "%s"), "arg1", "arg2", "arg3");
System.out.println(result); //www.test.com/blabla/?p1=arg1?p2=arg2?p3=arg3
Edit:
Just a brief explanation of what this does, it replaces all the v1,v2,v3,v4,v5,v6,v7,v8,v9,v0 in the original url for %s and then uses this in the format method so you can attribute what you want it to be.

Related

Using regular expressions to rename a string

In java, I want to rename a String so it always ends with ".mp4"
Suppose we have an encoded link, looking as follows:
String link = www.somehost.com/linkthatIneed.mp4?e=13974etc...
So, how do I rename the link String so it always ends with ".mp4"?
link = www.somehost.com/linkthatIneed.mp4 <--- that's what I need the final String to be.
Just get the string until the .mp4 part using the following regex:
^(.*\.mp4)
and the first captured group is what you want.
Demo: http://regex101.com/r/zQ6tO5
Another way to do this would be to split the string with ".mp4" as a split char and then add it again :)
Something like :
String splitChar = ".mp4";
String link = "www.somehost.com/linkthatIneed.mp4?e=13974etcrezkhjk"
String finalStr = link.split(splitChar)[0] + splitChar;
easy to do ^^
PS: I prefer to pass by regex but it ask for more knowledge about regex ^^
Well you can also do this:
Match the string with the below regex
\?.*
and replace it with empty string.
Demo: http://regex101.com/r/iV1cZ8
Try below code,
private String trimStringAfterOccurance(String link, String occuranceString) {
Integer occuranceIndex = link.indexOf(occuranceString);
String trimmedString = (String) link.subSequence(0, occuranceIndex + occuranceString.length() );
System.out.println(trimmedString);
return trimmedString;
}

Get URL from string with text

I have a bunch of strings like this:
Some text, bla-bla http://www.easypolls.net/poll.html?p=51e5a300e4b084575d8568bb#.UeWjBcCzaaA.twitter
And I need to parse this String to two:
Some text, bla-bla
http://www.easypolls.net/poll.html?p=51e5a300e4b084575d8568bb#.UeWjBcCzaaA.twitter
I need separate them, but, of course, it's enough to parse only URL.
Can you help me, how can I parse url from string like this.
By using split :
String str = "Some text, bla-bla http://www.easypolls.net/poll.html?p=51e5a300e4b084575d8568bb#.UeWjBcCzaaA.twitter";
String [] ar = str.split("http\\.*");
System.out.println(ar[0]);
System.out.println("http"+ar[1]);
This depends on how robust you want your parser to be. If you can reasonably expect every url to start with http://, then you can use
string.indexOf("http://");
This returns the index of the first character of the string you pass in (and -1 if the string does not appear).
Full code to return a substring with just the URL:
string.substring(string.indexOf("http://"));
Here's the documentation for Java's String class. Let this become your friend in programming! http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Try something like this:
String string = "sometext http://www.something.com";
String url = string.substring(string.indexOf("http"), string.length());
System.out.println(url);
or use split.
I know in PHP you'd be able to run the explode() (http://www.php.net/manual/en/function.explode.php) function. You'd choose which character you want to explode at. For instance, you could explode at "http://"
So running the code via PHP would look like:
$string = "Some text, bla-bla http://www.easypolls.net/poll.html?p=51e5a300e4b084575d8568bb#.UeWjBcCzaaA.twitter";
$pieces = explode("http://", $string);
echo $pieces[0]; // Would print "Some text, bla-bla"
echo $pieces[1]; // Would print "www.easypolls.net/poll.html?p=51e5a300e4b084575d8568bb#.UeWjBcCzaaA.twitter"

How to extract a url from a string in Java?

I have a string containing a short-code which looks like the one below:
some text...
[video url="http://www.example.com/path/to/my/video.ext"]
...some more text...
I want to be able to first check if the string contains that short-code and second extract the URL from it in Java (specifically Android).
use this regex for checking and grabbing url:
\[\w+\s+url="(?<urllink>)[^"]*"\s*]
and get gorup named urllink
try as:
String str = "[video url=\"http://www.example.com/path/to/my/video.ext\"]";
if (str.contains("url=\""))
{
int indexoff = str.indexOf("url=\"");
int indexofff = str.indexOf("\"]");
String strurl = str.substring(indexoff, indexofff - indexoff);
strurl = strurl.Replace("url=\"", ""); //get url string here
}
Android provides several function for this purpose. SOme of this are:
http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html
http://developer.android.com/reference/org/apache/http/client/utils/URLEncodedUtils.html
String url = "whatever"
Boolean myBool = url.contains("ate");
String contains. Not sure what extract url means, but the string class has lots of useful functions.
A powerful and maintainable manner it to Java URL.class, then, you can mix with Regex

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
What i would like returned would be /232222232/pageid
Now the 'myurl.com' can change but the /users/ will always be the same.
I suggest you use substring and 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 = 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.replaceAll(".*/users(/.*/.*)", "$1");
String rest = url.substring(url.indexOf("/users/") + 6);
You can use split(String regex,int limit) which will split the string around the pattern in regex at most limit times, so...
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".
You can use String.indexOf() and String.substring() in order to achieve this:
String pattern = "/users/";
String url = "http://myurl.com/users/232222232/pageid";
System.out.println(url.substring(url.indexOf(pattern)+pattern.length()-1);

Java: getting parameters from a URI who contains a file

let's say I have a file located in:
http://example.com/123.app
now I get the file name using the following (u is an entire url string):
String fileName = u.substring( u.lastIndexOf('/')+1, u.length() );
but I want to put on the same file name also parameters, so it'll look like, this:
http://example.com/123.app?id=87983
And I want to have a String fileName which will contain '123.app', and also String id which will contain '87983' and possibly more parameters.
How would I go about achieving this?
Firstly, take a look at this post, which uses the URL class to make working with the different parts of the URL string a lot easier.
Could you share a link to an URL parsing implementation?
Secondly, you would need to take the Query part of the URL and the Path part of the URL and substring the returned values to get the information that you desire. It should be pretty straight forward.
Use the API of URI! That's what it's for. Forget all this substring/regex/spit stuff.
you need to use the split method on string. So for example on your fileName string
String[] mystrings = fileName.split("?");
then mystrings[0] is your filename and mystrings[1] is your parameter
A simple way is : just repeat substring :
int qidx = filename.indexOf("?");
String realFilename = filename.substring(0, qidx);
String parameters = filename.substring(qidx+1);
and so on for parsing parameters.
If you are writing a servlet try :
String fileName = request.getServletPath();
and for the parameters somthing like
String id = request.getParameter("id");
Try this regex:
String s = "http://example.com/123.app?id=87983";
String[] split = s.split(".*/|\\?id=");
String filename = split[1];
String id = (split.length == 3) ? split[2] : null;

Categories

Resources