58

我正在构建一个正则表达式来检查一个单词是否以http://orhttps://或开头ftp://,我的代码如下,

     public static void main(String[] args) {
    try{
        String test = "http://yahoo.com";
        System.out.println(test.matches("^(http|https|ftp)://"));
    } finally{

    }
}

它打印false。我还检查了 stackoverflow post Regex 以测试字符串是否以 http:// 或 https:// 开头

正则表达式似乎是正确的,但为什么不匹配?我什至尝试^(http|https|ftp)\://^(http|https|ftp)\\://

4

5 回答 5

100

你需要一个完整的输入匹配。

System.out.println(test.matches("^(http|https|ftp)://.*$")); 

编辑:(基于@davidchambers的评论)

System.out.println(test.matches("^(https?|ftp)://.*$")); 
于 2011-11-09T06:48:34.250 回答
35

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

bool matches = test.startsWith("http://")
            || test.startsWith("https://") 
            || test.startsWith("ftp://");

如果这也更快,我也不会感到惊讶。

于 2011-11-09T06:54:28.457 回答
5

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

System.out.println(test.matches("^(?i)(https?|ftp)://.*$")); 
于 2014-09-09T03:31:02.633 回答
4

我认为正则表达式/字符串解析解决方案很棒,但是对于这个特定的上下文,使用 java 的 url 解析器似乎是有意义的:

https://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html

取自该页面:

import java.net.*;
import java.io.*;

public class ParseURL {
    public static void main(String[] args) throws Exception {

        URL aURL = new URL("http://example.com:80/docs/books/tutorial"
                           + "/index.html?name=networking#DOWNLOADING");

        System.out.println("protocol = " + aURL.getProtocol());
        System.out.println("authority = " + aURL.getAuthority());
        System.out.println("host = " + aURL.getHost());
        System.out.println("port = " + aURL.getPort());
        System.out.println("path = " + aURL.getPath());
        System.out.println("query = " + aURL.getQuery());
        System.out.println("filename = " + aURL.getFile());
        System.out.println("ref = " + aURL.getRef());
    }
}

产生以下结果:

protocol = http
authority = example.com:80
host = example.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING
于 2018-05-11T12:07:50.947 回答
1

test.matches() 方法检查所有 text.use test.find()

于 2011-11-09T06:53:27.707 回答