Use regular expressions to verify whether the Url address starts with http:// or https://

Use Java regular expressions (Regular Expressions) to verify whether a URL address begins with "http://" or "https://". The sample code is as follows:

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);
    }
}

In the above code, we use ^https?://.*$part of the regular expression to perform the matching, where:

  • ^Represents the starting position of the string
  • httpIndicates matching "http" string
  • s?Indicates that the "s" character is optional
  • ://Indicates matching "://" string
  • .*means match any number of characters
  • $Indicates the end position of the string

This regular expression means: any string starting with "http://" or "https://".

We use matches()the method to determine whether a string matches a regular expression. Returns if the match is successful, trueotherwise false.

Guess you like

Origin blog.csdn.net/ck3345143/article/details/130721698