使用正则验证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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值