正则校验URL是否以http和https 开头

    public static void main(String[] args) {

        String str = "hTTP://127.0.0.1:3000/abc/test.php";
        //转换为小写
        // str = str.toLowerCase();
        String regex ="^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\\\\\\\/])+$";
        boolean matches = str.matches(regex);
        System.out.println(matches);
    }

注意: 亲测 该正则不区分http和https的大小写问题,  例如 hTTP或hTtp 等 都显示true

以下是使用正则表达式校验URL格式的示例代码: ```python import re def is_valid_url(url: str) -> bool: regex = re.compile( r'^https?://' # http:// 或 https:// 开头 r'(?:(?:[A-Z0-9_](?:[A-Z0-9_-]{0,61}[A-Z0-9_])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # 域名部分 r'localhost|' # 或者是本地地址 r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # 或者是IP地址 r'(?::\d+)?' # 端口号(可选) r'(?:/?|[/?]\S+)$', re.IGNORECASE) return bool(regex.match(url)) # 测试示例 print(is_valid_url('http://www.example.com')) # True print(is_valid_url('https://example.com/path/to/page.html')) # True print(is_valid_url('ftp://example.com/path/to/file.txt')) # False print(is_valid_url('http://localhost:8080')) # True print(is_valid_url('http://127.0.0.1')) # True ``` 该函数使用了一个较为复杂的正则表达式,可以较为准确地校验URL的格式。其中,该正则表达式包含以下几个部分: 1. `^https?://`:以 `http://` 或 `https://` 开头。 2. `(?:...|...)`:表示两个或多个可选的匹配项。 3. `[A-Z0-9_](?:[A-Z0-9_-]{0,61}[A-Z0-9_])?\.`:匹配域名中的一级多级子域名,例如 `www.`、`blog.` 等。 4. `(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)`:匹配顶级域名,例如 `.com`、`.co.uk` 等。 5. `localhost`:匹配本地地址。 6. `\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}`:匹配IP地址。 7. `(?::\d+)?`:匹配可选的端口号。 8. `(?:/?|[/?]\S+)$`:匹配可选的路径查询参数。 如果URL符合以上规则,则返回 `True`,否则返回 `False`。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值