Reputation: 21893
String url = "mysite.com/index.php?name=john&id=432"
How can I extract the id parameter (432)?
it can be in any position in the url and the length of the id varies too
Upvotes: 1
Views: 14465
Reputation: 2548
I just give an abstract regex. add anything you don't want in id
after [^&
Pattern pattern = Pattern.compile("id=([^&]*?)$|id=([^&]*?)&");
Matcher matcher = pattern.matcher(url);
if (matcher.matches()) {
int idg1 = Integer.parseInt(matcher.group(1));
int idg2 = Integer.parseInt(matcher.group(2));
}
either idg1
or idg2
has value.
Upvotes: 3
Reputation: 1757
The regex has already been given, but you can do it with some simple splitting too:
public static String getId(String url) {
String[] params = url.split("\\?");
if(params.length==2) {
String[] keyValuePairs = params[1].split("&");
for(String kvp : keyValuePairs) {
String[] kv = kvp.split("=");
if(kv[0].equals("id")) {
return kv[1];
}
}
}
throw new IllegalStateException("id not found");
}
Upvotes: 0
Reputation: 5614
You can use Apache URLEncodedUtils from HttpClient package:
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import java.nio.charset.Charset;
import java.util.List;
public class UrlParsing {
public static void main(String[] a){
String url="http://mysite.com/index.php?name=john&id=42";
List<NameValuePair> args= URLEncodedUtils.parse(url, Charset.defaultCharset());
for (NameValuePair arg:args)
if (arg.getName().equals("id"))
System.out.println(arg.getValue());
}
}
This print 42 to the console.
If you have the url stored in a URI object, you may find useful an overload of URLEncodedUtils.parse that accept directly an URI instance. If you use this overloaded version, you have to give the charset as a string:
URI uri = URI.create("http://mysite.com/index.php?name=john&id=42");
List<NameValuePair> args= URLEncodedUtils.parse(uri, "UTF-8");
Upvotes: 6
Reputation: 785146
You can use:
String id = url.replaceAll("^.*?(?:\\?|&)id=(\\d+)(?:&|$).*$", "$1");
Upvotes: 0