Matcher in appendReplacement () Contact with replaceAll () method

https://blog.csdn.net/mjlfto/article/details/53896981

package com.mjlf.myBatis.accessControl.regex;

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

/**
 * Created by a123 on 16/12/27.
 */
public class Test {

    public static void main(String[] args){
        Pattern p = Pattern.compile("java");
        Matcher m = p.matcher("The java book is java program book c");
        StringBuffer sb = new StringBuffer();

        if(m.find()){
            m.appendReplacement(sb,"python");
        }
        System.out.println(sb);

        if(m.find()){
            m.appendReplacement(sb,"python");
        }
        System.out.println(sb);

        if(m.find()){
            m.appendReplacement(sb,"python");
        }
        System.out.println(sb);

        System.out.println(m.replaceAll("c++"));
    }
}
/**
The python
The python book is python
The python book is python
The c++ book is c++ program book c
*/

replace all:

public String replaceAll(String replacement) {
        reset();
        boolean result = find();
        if (result) {
            StringBuffer sb = new StringBuffer();
            do {
                appendReplacement(sb, replacement);
                result = find();
            } while (result);
            appendTail(sb);
            return sb.toString();
        }
        return text.toString();
    }

 

Guess you like

Origin www.cnblogs.com/brxHqs/p/11671217.html
Recommended