要检查的正则表达式以http://,https://或ftp://开头

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)

  • 你也可以使用`(https?| ftp)`如果愿意的话. (10认同)
  • @adhg` $`表示行尾.`.*`匹配任何字符零次或多次. (2认同)

Ran*_*ook 34

除非有一些令人信服的理由使用正则表达式,否则我只会使用String.startsWith:

bool matches = test.startsWith("http://")
            || test.startsWith("https://") 
            || test.startsWith("ftp://");
Run Code Online (Sandbox Code Playgroud)

如果速度更快,我也不会感到惊讶.

  • 如果这不慢(与编译的正则表达式相比),我会感到惊讶,但必须进行测试才能找到答案. (3认同)

use*_*877 5

如果您想以不区分大小写的方式执行此操作,则更好:

System.out.println(test.matches("^(?i)(https?|ftp)://.*$")); 
Run Code Online (Sandbox Code Playgroud)