Java Pattern.matches 方法
上次修改时间:2025 年 4 月 20 日
Pattern.matches
方法是 Java 正则表达式 API 中的一个静态实用程序。 它提供了一种快速的方法来检查字符串是否与正则表达式模式匹配。 该方法一步完成模式的编译和与输入的匹配。
此方法适用于简单的一次性模式匹配操作。 对于重复匹配,单独编译模式更有效。 如果整个输入序列与模式匹配,该方法返回 true。
Pattern.matches 方法概述
Pattern.matches
方法具有以下签名:public static boolean matches(String regex, CharSequence input)
。 它接受一个正则表达式模式和一个输入字符串,并返回一个布尔值结果。
在内部,它编译模式并为输入创建一个匹配器。 该方法等效于 Pattern.compile(regex).matcher(input).matches
。 如果正则表达式语法无效,它会抛出 PatternSyntaxException。
基本模式匹配示例
此示例演示了 Pattern.matches
的最简单用法。 我们检查字符串是否与基本模式匹配。 该模式使用文字字符,不包含特殊的正则表达式构造。
package com.zetcode; import java.util.regex.Pattern; public class BasicMatch { public static void main(String[] args) { String input = "Hello World"; String regex = "Hello World"; boolean isMatch = Pattern.matches(regex, input); System.out.println("Exact match: " + isMatch); regex = "Hello.*"; isMatch = Pattern.matches(regex, input); System.out.println("Pattern match: " + isMatch); } }
第一个检查验证输入和模式之间的精确匹配。 第二个使用 .*
正则表达式构造来匹配 "Hello" 之后的任何字符。 在此示例中,两种模式都与输入字符串匹配。
电子邮件验证示例
此示例展示了如何使用 Pattern.matches
验证电子邮件地址。 正则表达式模式遵循常见的电子邮件验证规则,同时保持简单。
package com.zetcode; import java.util.regex.Pattern; public class EmailValidation { public static void main(String[] args) { String[] emails = { "user@example.com", "first.last@domain.co", "invalid.email@", "missing@tld", "name@123.123.123.123" }; String regex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$"; for (String email : emails) { boolean isValid = Pattern.matches(regex, email); System.out.printf("%-25s: %s%n", email, isValid); } } }
正则表达式模式检查 @ 符号之前的字母数字字符。 在 @ 之后,它需要一个至少包含一个点的域名。 这是一种基本验证,可以捕获明显的错误,但可能会允许一些无效的地址。
电话号码验证示例
此示例演示了使用不同格式的电话号码验证。 该模式适用于可选的国家/地区代码和各种分隔符。
package com.zetcode; import java.util.regex.Pattern; public class PhoneValidation { public static void main(String[] args) { String[] phones = { "+1 (123) 456-7890", "123.456.7890", "123-456-7890", "(123)4567890", "1234567890", "123-45-6789" }; String regex = "^\\+?\\d{1,3}?[-.\\s]?\\(?\\d{3}\\)?[-.\\s]?\\d{3}[-.\\s]?\\d{4}$"; for (String phone : phones) { boolean isValid = Pattern.matches(regex, phone); System.out.printf("%-20s: %s%n", phone, isValid); } } }
正则表达式模式很复杂但很灵活。 它处理可选的国家/地区代码、区号周围的括号以及各种分隔符。 最后一个测试用例显示了一个无效的社会安全号码模式,验证失败。
日期格式验证示例
此示例使用 Pattern.matches
验证不同格式的日期。 该模式检查常见的日期格式,同时确保有效的日/月值。
package com.zetcode; import java.util.regex.Pattern; public class DateValidation { public static void main(String[] args) { String[] dates = { "2023-12-31", "12/31/2023", "31-12-2023", "2023/12/31", "02-29-2023", // Invalid (not a leap year) "13-01-2023" // Invalid month }; String regex = "^(?:(?:19|20)\\d\\d)[-/](?:(?:0[1-9]|1[0-2])[-/](?:0[1-9]|[12][0-9]|3[01])|(?:0[1-9]|[12][0-9]|3[01])[-/](?:0[1-9]|1[0-2]))$"; for (String date : dates) { boolean isValid = Pattern.matches(regex, date); System.out.printf("%-15s: %s%n", date, isValid); } } }
正则表达式模式验证 YYYY-MM-DD、MM/DD/YYYY 和 DD-MM-YYYY 格式的日期。 它检查有效的月份 (1-12) 和日期 (1-31),但不验证所有日历规则(例如闰年中的二月天数)。
密码强度检查示例
此示例使用多个带有 Pattern.matches
的正则表达式模式检查密码强度。 每个模式测试不同的复杂性要求。
package com.zetcode; import java.util.regex.Pattern; public class PasswordStrength { public static void main(String[] args) { String[] passwords = { "weak", "Better1", "Str0ngP@ss", "NoNumbers!", "LongEnoughButNoSpecialChars123" }; // At least 8 chars, one uppercase, one lowercase, one digit String mediumRegex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,}$"; // Medium requirements plus one special character String strongRegex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&]).{8,}$"; for (String pwd : passwords) { boolean isMedium = Pattern.matches(mediumRegex, pwd); boolean isStrong = Pattern.matches(strongRegex, pwd); String strength; if (isStrong) strength = "Strong"; else if (isMedium) strength = "Medium"; else strength = "Weak"; System.out.printf("%-30s: %s%n", pwd, strength); } } }
该示例使用正向预查 ((?=...)
) 来检查字符类要求,而无需消耗输入。 中等模式需要长度、大小写和数字规则。 强模式添加了特殊字符要求。
URL 验证示例
此示例使用 Pattern.matches
验证具有不同协议和格式的 URL。 该模式检查有效的 URL 结构。
package com.zetcode; import java.util.regex.Pattern; public class UrlValidation { public static void main(String[] args) { String[] urls = { "https://www.example.com", "https://:8080", "ftp://files.example.org", "www.missing.protocol.com", "https://example.com/path?query=param", "invalid url" }; String regex = "^(https?|ftp)://[\\w\\-]+(\\.[\\w\\-]+)+([\\w\\-.,@?^=%&:/~+#]*[\\w\\-@?^=%&/~+#])?$"; for (String url : urls) { boolean isValid = Pattern.matches(regex, url); System.out.printf("%-35s: %s%n", url, isValid); } } }
该正则表达式验证具有 http、https 或 ftp 协议的 URL。 它需要一个至少包含一个点的域名,并允许可选的路径、查询和片段。 该模式拒绝没有协议和格式错误的域名的 URL。
信用卡验证示例
此示例使用 Pattern.matches
以及不同卡类型的模式来验证信用卡号码。 它检查格式并执行 Luhn 校验。
package com.zetcode; import java.util.regex.Pattern; public class CreditCardValidation { public static void main(String[] args) { String[] cards = { "4111-1111-1111-1111", // Visa "5500-0000-0000-0004", // MasterCard "3400-0000-0000-009", // American Express "6011-0000-0000-0004", // Discover "1234-5678-9012-3456", // Invalid "4111111111111111" // Visa no hyphens }; String visaRegex = "^4[0-9]{12}(?:[0-9]{3})?$"; String mastercardRegex = "^5[1-5][0-9]{14}$"; String amexRegex = "^3[47][0-9]{13}$"; String discoverRegex = "^6(?:011|5[0-9]{2})[0-9]{12}$"; for (String card : cards) { // Remove hyphens for validation String cleanCard = card.replaceAll("-", ""); boolean isValid = false; String cardType = "Unknown"; if (Pattern.matches(visaRegex, cleanCard)) { isValid = true; cardType = "Visa"; } else if (Pattern.matches(mastercardRegex, cleanCard)) { isValid = true; cardType = "MasterCard"; } else if (Pattern.matches(amexRegex, cleanCard)) { isValid = true; cardType = "American Express"; } else if (Pattern.matches(discoverRegex, cleanCard)) { isValid = true; cardType = "Discover"; } System.out.printf("%-25s: %-16s %s%n", card, cardType, isValid ? "Valid" : "Invalid"); } } }
该示例首先从卡号中删除连字符。 然后,它根据主要卡类型的模式检查每张卡。 这些模式验证起始数字和长度要求。 请注意,这不会验证 Luhn 校验和以供实际使用。
来源
在本文中,我们通过七个实际示例探讨了 Pattern.matches
方法。 这些演示了常见的验证场景,其中正则表达式模式匹配在 Java 应用程序中很有用。
作者
列出所有Java教程。