要检查的正则表达式以 http://、https:// 或 ftp:// 开头
我正在构建一个正则表达式来检查单词是否以 http://
或 https://
或 ftp://
开头,我的代码如下,
public static void main(String[] args) {
try{
String test = "http://yahoo.com";
System.out.println(test.matches("^(http|https|ftp)://"));
} finally{
}
}
它打印false
。我还检查了 stackoverflow 帖子 正则表达式来测试字符串是否以以下开头http:// 或 https://
正则表达式似乎是正确的,但为什么它不匹配?我什至尝试了 ^(http|https|ftp)\://
和 ^(http|https|ftp)\\://
I am framing a regex to check if a word starts with http://
or https://
or ftp://
, my code is as follows,
public static void main(String[] args) {
try{
String test = "http://yahoo.com";
System.out.println(test.matches("^(http|https|ftp)://"));
} finally{
}
}
It prints false
. I also checked stackoverflow post Regex to test if string begins with http:// or https://
The regex seems to be right but why is it not matching?. I even tried ^(http|https|ftp)\://
and ^(http|https|ftp)\\://
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您需要在此处进行整个输入匹配。
编辑:(基于@davidchambers的评论)
You need a whole input match here.
Edit:(Based on @davidchambers's comment)
除非有一些令人信服的理由使用正则表达式,否则我只会使用 String.startsWith:
如果这也更快,我不会感到惊讶。
Unless there is some compelling reason to use a regex, I would just use String.startsWith:
I wouldn't be surprised if this is faster, too.
如果您想以不区分大小写的方式执行此操作,则更好:
If you wanna do it in case-insensitive way, this is better:
我认为正则表达式/字符串解析解决方案很棒,但对于这个特定的上下文,似乎仅使用 java 的 url 解析器就有意义:
https://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html
取自该页面:
产量 下列:
I think the regex / string parsing solutions are great, but for this particular context, it seems like it would make sense just to use java's url parser:
https://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html
Taken from that page:
yields the following:
test.matches() 方法检查所有文本。use test.find()
test.matches() method checks all text.use test.find()
在startsWith和matches之间添加验证。
开始于:3755625
开始于:true
匹配:174250
matches:true
matches 为 174us,startswith 为 3.755ms
matches 在场景中的性能和代码整洁度上比startsWith 好得多。
Add a verification between startsWith and matches.
startsWith:3755625
startsWith:true
matches:174250
matches:true
matches is 174us, startswith is 3.755ms
matches is much better than startsWith on performance and code cleanness in the scenario.