Java 正则表达式:包含字符串
在 Java 中,使用正则表达式来检查一个字符串是否包含特定模式或子字符串,可以通过 String.matches()、Pattern 和 Matcher 类来实现,以下是几种常见的方法:

使用 String.matches()
String text = "Hello, world!";
boolean contains = text.matches(".*world.*"); // 检查是否包含"world"
System.out.println(contains); // 输出: true
使用 Pattern 和 Matcher
import java.util.regex.*;
String text = "Hello, world!";
Pattern pattern = Pattern.compile("world");
Matcher matcher = pattern.matcher(text);
boolean contains = matcher.find(); // 查找是否存在匹配
System.out.println(contains); // 输出: true
检查是否包含多个可能字符串
String text = "Hello, world!";
boolean contains = text.matches(".*(world|java|regex).*");
System.out.println(contains); // 输出: true
不区分大小写的检查
String text = "Hello, World!";
Pattern pattern = Pattern.compile("world", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(text);
boolean contains = matcher.find();
System.out.println(contains); // 输出: true
检查是否包含数字
String text = "Order 12345";
boolean containsNumber = text.matches(".*\\d+.*"); // \d 匹配数字
System.out.println(containsNumber); // 输出: true
检查是否包含特定格式的字符串
String text = "Email: example@domain.com";
boolean containsEmail = text.matches(".*\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b.*");
System.out.println(containsEmail); // 输出: true
注意事项
String.matches()要求整个字符串匹配正则表达式,所以通常需要使用 前后缀来表示"包含"- 对于复杂的正则表达式,使用
Pattern和Matcher更灵活 - 正则表达式中的特殊字符需要转义, 需要写成
\\.
性能考虑
如果需要多次使用同一个正则表达式,建议预编译 Pattern 对象:
Pattern pattern = Pattern.compile("your regex");
// 然后多次使用 pattern.matcher()
这样比每次调用 String.matches() 都重新编译正则表达式更高效。

