通往匹配任意字符之道的终极指南:Java 中的通配符174


在 Java 编程中,有时我们需要匹配任意字符或一组字符。为此,可以使用通配符。通配符是特殊字符,用于表示不同类型的匹配模式。

.*:匹配任意字符序列

通配符 .* 用于匹配任何字符(包括换行符)的任意序列。它是通配符家族中最通用的成员,因为它可以匹配任意长度的任意字符组合。
import ;
import ;
public class MatchAnyCharacterSequence {
public static void main(String[] args) {
String input = "This is a sample string.";
String pattern = ".*";
Pattern r = (pattern);
Matcher m = (input);
if (()) {
("匹配成功:" + (0));
} else {
("匹配失败");
}
}
}

.:匹配任意单个字符

通配符 . 专门用来匹配任何单个字符(除了换行符)。它不匹配空字符串,因此它总是匹配一些东西。
import ;
import ;
public class MatchAnySingleCharacter {
public static void main(String[] args) {
String input = "This is a sample string.";
String pattern = ".";
Pattern r = (pattern);
Matcher m = (input);
while (()) {
("匹配成功:" + (0));
}
}
}

?:匹配零个或一个字符

通配符 ? 匹配零个或一个字符。它提供了匹配单个字符的灵活度,同时允许它在某些情况下缺失。
import ;
import ;
public class MatchZeroOrOneCharacter {
public static void main(String[] args) {
String input = "This is a sample string.";
String pattern = "s?";
Pattern r = (pattern);
Matcher m = (input);
while (()) {
("匹配成功:" + (0));
}
}
}

[...]:匹配字符集

通配符 [...] 用于匹配一组预定义的字符。方括号内包含的字符集合可以是单个字符、字符范围或它们的组合。
import ;
import ;
public class MatchCharacterSet {
public static void main(String[] args) {
String input = "This is a sample string.";
String pattern = "[st]";
Pattern r = (pattern);
Matcher m = (input);
while (()) {
("匹配成功:" + (0));
}
}
}

[^...]:匹配字符集的反转

通配符 [^...] 与 [...] 类似,但它匹配方括号内字符集合之外的任意字符。换句话说,它匹配不在指定字符集中的任何字符。
import ;
import ;
public class MatchCharacterSetComplement {
public static void main(String[] args) {
String input = "This is a sample string.";
String pattern = "[^st]";
Pattern r = (pattern);
Matcher m = (input);
while (()) {
("匹配成功:" + (0));
}
}
}

例子

以下是一些使用通配符的示例:
.*dog.*:匹配包含 "dog" 字符串的任何字符串。
fo.:匹配以 "fo" 开头且后面跟任意字符的字符串。
a?le:匹配以 "a" 开头且后面可能跟或不跟 "le" 的字符串。
[abc]at:匹配以 "a"、"b" 或 "c" 开头且以 "at" 结尾的字符串。
[^xyz]:匹配不包含 "x"、"y" 或 "z" 的任何字符。


通配符是 Java 中强大的工具,用于匹配任意字符或字符序列。它们提供了匹配模式的灵活性和表达能力,这在各种文本处理和数据验证应用程序中非常有用。通过理解和熟练使用这些通配符,您可以有效地编写正则表达式以满足您特定的匹配需求。

2024-12-05


上一篇:Java 并发的大数据处理

下一篇:Java 中高效解析 XML