Abh*_*hek 47 java regex startswith
我制定一个正则表达式来检查,如果一个单词开头http://或https://或者ftp://,我的代码如下,
public static void main(String[] args) {
try{
String test = "http://yahoo.com";
System.out.println(test.matches("^(http|https|ftp)://"));
} finally{
}
}
Run Code Online (Sandbox Code Playgroud)
它打印false.我还检查了在Regex上发布的stackoverflow,以测试字符串是否以http://或https://开头
正则表达式似乎是正确的,但为什么它不匹配?我甚至尝试^(http|https|ftp)\://和^(http|https|ftp)\\://
Pri*_*ley 87
你需要一个完整的输入匹配.
System.out.println(test.matches("^(http|https|ftp)://.*$"));
Run Code Online (Sandbox Code Playgroud)
编辑 :(基于@davidchambers的评论)
System.out.println(test.matches("^(https?|ftp)://.*$"));
Run Code Online (Sandbox Code Playgroud)
Ran*_*ook 34
除非有一些令人信服的理由使用正则表达式,否则我只会使用String.startsWith:
bool matches = test.startsWith("http://")
|| test.startsWith("https://")
|| test.startsWith("ftp://");
Run Code Online (Sandbox Code Playgroud)
如果速度更快,我也不会感到惊讶.
如果您想以不区分大小写的方式执行此操作,则更好:
System.out.println(test.matches("^(?i)(https?|ftp)://.*$"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
105359 次 |
| 最近记录: |