[英]How can I write to check a URL?
A friend of mine requested to write a simple code to check whether a URL ends with asp or not.我的一个朋友要求编写一个简单的代码来检查 URL 是否以 asp 结尾。 I am thinking about accepting the URL as string and checking the last tree letters if it's as or not.
我正在考虑接受 URL 作为字符串,并检查最后一个树字母是否正确。 I just want to check is there any ways to write this code.
我只想检查是否有任何方法可以编写此代码。 (of course there are plenty of ways but it need to be simple)
(当然有很多方法,但要简单)
Thanks in advance提前致谢
String url = ...
if(url.endsWith(".asp")){
// do your thing
}
You will probably want to use the String.endsWith()
method.您可能想要使用
String.endsWith()
方法。
if (s.endsWith("asp")) {
System.out.println("Yes");
} else {
System.out.println("No");
}
If you really want to do this properly, you can parse the string as a real java.net.URL
and extract the path using getPath()
.如果您真的想正确执行此操作,可以将字符串解析为真正的
java.net.URL
并使用getPath()
提取路径。
URL url = new URL(s);
String path = url.getPath();
if (path.endsWith("asp")) {
System.out.println("Yes");
} else {
System.out.println("No");
}
Use a regular expression:使用正则表达式:
.*\.asp(x){0,1}(\?){0,1}.*
This will handle these cases:这将处理这些情况:
A regex would be a solution though I find them extremely ugly in Java.尽管我在 Java 中发现它们非常丑陋,但正则表达式将是一个解决方案。
String url = ....
if (Pattern.compile("\.asp[^\.]*\z").matcher(url).matches()){
//do your thing
}
Yuk indeed.确实是的。 And i'm not sure if I got the regex right
而且我不确定我的正则表达式是否正确
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.