温馨提示×

replaceAll与Pattern配合使用

小樊
84
2024-06-27 17:04:26
栏目: 编程语言

replaceAll 方法可与 Pattern 配合使用来替换字符串中的指定文本。以下是一个示例:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String text = "Hello, World! This is a test string.";
        
        // 创建一个正则表达式匹配模式,匹配所有小写字母
        Pattern pattern = Pattern.compile("[a-z]");
        
        // 创建一个Matcher对象,用于匹配文本
        Matcher matcher = pattern.matcher(text);
        
        // 使用replaceAll方法替换匹配到的小写字母为大写字母
        String result = matcher.replaceAll(match -> match.group().toUpperCase());
        
        System.out.println(result);
    }
}

在上面的示例中,我们首先创建了一个正则表达式匹配模式 [a-z],该模式用于匹配所有小写字母。然后,我们使用 Pattern 类的 matcher 方法创建了一个 Matcher 对象来匹配文本。最后,我们使用 replaceAll 方法结合 lambda 表达式来替换匹配到的小写字母为大写字母。

输出结果为:

HHeLLo, WoRLD! THis is a TeST STRinG.

0