In-depth analysis of Java regular expression syntax requires specific code examples
Regular expression is a powerful pattern matching tool that is used in various programming languages. Has been widely used. In Java, we can use the classes provided by the java.util.regex package to implement regular expression functions. This article will delve into the syntax of Java regular expressions and illustrate it with specific code examples.
1. Basic syntax
2. Common character classes
3. Example analysis
The following uses several examples to further analyze the syntax of Java regular expressions.
import java.util.regex.Matcher; import java.util.regex.Pattern; public class EmailValidator { private static final String EMAIL_REGEX = "^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$"; public static boolean validateEmail(String email) { Pattern pattern = Pattern.compile(EMAIL_REGEX); Matcher matcher = pattern.matcher(email); return matcher.matches(); } public static void main(String[] args) { String[] emails = {"abc@163.com", "xyz@gmail.com", "invalidemail", "123456"}; for (String email : emails) { System.out.println(email + ": " + validateEmail(email)); } } }
import java.util.regex.Matcher; import java.util.regex.Pattern; public class URLParser { private static final String URL_REGEX = "^(https?)://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$"; public static void parseURL(String url) { Pattern pattern = Pattern.compile(URL_REGEX); Matcher matcher = pattern.matcher(url); if (matcher.matches()) { System.out.println("Protocol: " + matcher.group(1)); System.out.println("Hostname: " + matcher.group(2)); System.out.println("Path: " + matcher.group(3)); } else { System.out.println("Invalid URL format"); } } public static void main(String[] args) { String[] urls = {"http://www.example.com/path/to/page.html", "https://www.example.com/", "invalidurl"}; for (String url : urls) { System.out.println("URL: " + url); parseURL(url); System.out.println(); } } }
The above code examples demonstrate how to use regular expressions to verify email addresses and extract information from URLs. Through an in-depth analysis of Java regular expression syntax and combined with specific code examples, I believe readers have a deeper understanding of the use of Java regular expressions. Hope this article is helpful to you.
The above is the detailed content of A Deep Dive into Java Regular Expression Syntax. For more information, please follow other related articles on the PHP Chinese website!