使用正则验证Url地址是否以http:// 或 https:// 开头

使用 Java 正则表达式 (Regular Expressions) 来验证一个 URL 地址是否以 "http://" 或者 "https://" 开头。示例代码如下:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String url1 = "https://www.example.com";
        String url2 = "ftp://www.example.com";
        String url3 = "http://www.example.com";
        
        // 验证 url1 是否以 http:// 或 https:// 开头
        boolean isMatch1 = url1.matches("^https?://.*$");
        System.out.println(url1 + " 是否匹配: " + isMatch1);
        
        // 验证 url2 是否以 http:// 或 https:// 开头
        boolean isMatch2 = url2.matches("^https?://.*$");
        System.out.println(url2 + " 是否匹配:" + isMatch2);
          
        // 验证 url3 是否以 http:// 或 https:// 开头
        boolean isMatch3 = url3.matches("^https?://.*$");
        System.out.println(url3 + " 是否匹配: " + isMatch3);
    }
}

在上述代码中,我们使用了正则表达式的 ^https?://.*$ 部分来进行匹配,其中:

  • ^ 表示字符串起始位置
  • http 表示匹配 "http" 字符串
  • s? 表示 "s" 字符可有可无
  • :// 表示匹配 "://" 字符串
  • .* 表示匹配任意数量的字符
  • $ 表示字符串结束位置

这个正则表达式的意思是:以 "http://" 或 "https://" 开头的任意字符串。

我们通过 matches() 方法来判断一个字符串是否匹配正则表达式。如果匹配成功,返回 true,反之则为 false

猜你喜欢

转载自blog.csdn.net/ck3345143/article/details/130721698
今日推荐