Regex to check with starts with http://, https:// or ftp:// in java

Regex to check with starts with http://, https:// or ftp:// in java

You can use a regular expression (regex) in Java to check if a string starts with "http://", "https://", or "ftp://". Here's a regex pattern for this purpose:

^(http://|https://|ftp://) 

In this regex pattern:

  • ^ asserts the start of the string.
  • (http://|https://|ftp://) is a group that matches one of the specified prefixes: "http://", "https://", or "ftp://".

Here's how you can use this regex pattern in Java to check if a string starts with one of these prefixes:

import java.util.regex.*; public class URLPrefixCheck { public static void main(String[] args) { String input = "https://www.example.com"; // Define the regex pattern String pattern = "^(http://|https://|ftp://)"; // Compile the pattern Pattern regex = Pattern.compile(pattern); // Match the input against the pattern Matcher matcher = regex.matcher(input); if (matcher.find()) { System.out.println("String starts with a valid URL prefix."); } else { System.out.println("String does not start with a valid URL prefix."); } } } 

In this example, the Pattern class is used to compile the regex pattern, and the Matcher class is used to match the input string against the pattern. If a match is found, it means the string starts with "http://", "https://", or "ftp://".


More Tags

object-detection-api servlet-filters macos-mojave magento apt-get read.csv lsusb combinations android-4.2-jelly-bean material-design-in-xaml

More Java Questions

More Chemistry Calculators

More Dog Calculators

More Physical chemistry Calculators

More Transportation Calculators