Java正则表达式函数示例
发布时间:2023-06-16 08:50:40
正则表达式是一种非常强大的工具,用于匹配和操作字符串。在Java中,我们可以使用正则表达式函数来处理字符串。
1. String.matches(String regex)
这个函数的作用是判断字符串是否匹配正则表达式regex。它返回一个Boolean值,如果匹配则为true,否则为false。
示例:
String str = "Hello, World!";
Boolean match = str.matches("^[A-Za-z, ]+$"); // 判断是否为字母、逗号和空格
System.out.println(match); // true
match = str.matches("^\\d+$"); // 判断是否为数字
System.out.println(match); // false
2. String.replaceAll(String regex, String replacement)
这个函数的作用是将字符串中匹配正则表达式regex的部分替换为replacement。它返回一个新的字符串,原字符串不会被修改。
示例:
String str = "Hello, World!";
String replaced = str.replaceAll(",", ""); // 将逗号替换为空字符串
System.out.println(replaced); // Hello World
replaced = str.replaceAll("\\b\\w{5}\\b", "*****"); // 将长度为5的单词替换为5个星号
System.out.println(replaced); // *****, World!
3. String.split(String regex)
这个函数的作用是将字符串按照正则表达式regex的规则分割成多个子串,并返回一个字符串数组。注意,分割符本身不包含在任何一个子串中。
示例:
String str = "Hello, World!";
String[] tokens = str.split(", "); // 将逗号和空格作为分隔符
for (String token : tokens) {
System.out.println(token);
}
输出:
Hello World!
4. Pattern.compile(String regex)和Matcher类
Pattern类表示一个正则表达式,可以通过Pattern.compile方法将字符串形式的正则表达式编译成Pattern对象。Matcher类用于对字符串进行匹配操作,可以通过Pattern对象的matcher方法获取Matcher对象。
示例:
String str = "Hello, World!";
Pattern pattern = Pattern.compile("\\b\\w{5}\\b"); // 匹配长度为5的单词
Matcher matcher = pattern.matcher(str);
while (matcher.find()) { // 找到所有匹配的子串
System.out.println(matcher.group()); // 输出匹配的子串
}
输出:
Hello World
5. Pattern和Matcher的更多方法
除了find和group方法,Pattern和Matcher类还提供了很多其他的方法来进行更复杂的匹配操作,比如matches、replaceAll、replaceFirst等。
示例:
String str = "Hello, World!";
Pattern pattern = Pattern.compile("\\b\\w{5}\\b"); // 匹配长度为5的单词
Matcher matcher = pattern.matcher(str);
Boolean match = matcher.matches(); // 判断整个字符串是否匹配该正则表达式
System.out.println(match); // false
String replaced = matcher.replaceAll("*****"); // 将所有长度为5的单词替换为5个星号
System.out.println(replaced); // *****, *****!
replaced = matcher.replaceFirst("*****"); // 将第一个长度为5的单词替换为5个星号
System.out.println(replaced); // *****, World!
Java正则表达式函数非常强大和灵活,可以帮助我们处理各种字符串操作。但是正则表达式的语法需要掌握,否则容易出现错误,建议多练习和使用。
