java 如何使用正则表达式获取此 URL 参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10728093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get this URL parameter with regex
提问by code511788465541441
String url = "mysite.com/index.php?name=john&id=432"
How can I extract the id parameter (432)?
如何提取 id 参数 (432)?
it can be in any position in the url and the length of the id varies too
它可以在 url 中的任何位置,并且 id 的长度也不同
回答by Andrea Parodi
You can use Apache URLEncodedUtilsfrom HttpClientpackage:
您可以使用Apache URLEncodedUtils从HttpClient的包:
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.
这将打印 42 到控制台。
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:
如果您将 url 存储在 URI 对象中,您可能会发现直接接受 URI 实例的 URLEncodedUtils.parse 的重载很有用。如果您使用此重载版本,则必须将字符集作为字符串提供:
URI uri = URI.create("http://mysite.com/index.php?name=john&id=42");
List<NameValuePair> args= URLEncodedUtils.parse(uri, "UTF-8");
回答by Darshana
I just give an abstract regex. add anything you don't want in id
after [^&
我只是给出一个抽象的正则表达式。添加任何你不想要的东西id
之后[^&
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.
任一idg1
或idg2
具有价值。
回答by anubhava
You can use:
您可以使用:
String id = url.replaceAll("^.*?(?:\?|&)id=(\d+)(?:&|$).*$", "");
回答by Matthijs Bierman
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");
}