e430. searching and replacing with nonconstant values using a regular expression.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 32 行

TXT
32
字号
The simplest way to replace all occurrences of a pattern in a CharSequence is to use Matcher.replaceAll(). However, this method is restricted to replacement values that are constant. If the replacement value is dynamic (e.g., converting the match to uppercase), Matcher.appendReplacement() must be used. 
This example demonstrates the use of Matcher.appendReplacement() by converting all words that match [a-zA-Z]+[0-9]+ to uppercase. 

    CharSequence inputStr = "ab12 cd efg34";
    String patternStr = "([a-zA-Z]+[0-9]+)";
    
    // Compile regular expression
    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher = pattern.matcher(inputStr);
    
    // Replace all occurrences of pattern in input
    StringBuffer buf = new StringBuffer();
    boolean found = false;
    while ((found = matcher.find())) {
        // Get the match result
        String replaceStr = matcher.group();
    
        // Convert to uppercase
        replaceStr = replaceStr.toUpperCase();
    
        // Insert replacement
        matcher.appendReplacement(buf, replaceStr);
    }
    matcher.appendTail(buf);
    
    // Get result
    String result = buf.toString();
    // AB12 cd EFG34

 Related Examples 

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?