正则表达式中appendReplacement和appendTail的用法

正则表达式中appendReplacement和appendTail的用法

在java Matcher类中提供了俩个方法,分别是appendReplacement和appendTail方法来对替换字符串进行操作,通过这俩个方法我们可以手动控制想要替换的次数以及替换的内容。

首先通过API查看一下appendReplacement的方法,看一下官方文档对这个方法的解释

public Matcher appendReplacement​(StringBuilder sb,String replacement)


This method performs the following actions:

 1. It reads characters from the input sequence, starting at the append
    position, and appends them to the given string buffer. It stops
    after reading the last character preceding the previous match, that
    is, the character at index start() - 1.


 2. It appends the given replacement string to the string buffer.


 3. It sets the append position of this matcher to the index of the last
    character matched, plus one, that is, to end().

说了半天也没有看懂官方的API文档在将什么,没关系~~,我们来用代码解释以下。

    public class Demo {
        public static void main(String[] args){
            StringBuilder sb= new StringBuilder();
            //匹配模式为([Tt])
            Pattern p = Pattern.compile("([Tt])");
            Matcher m = p.matcher("OK,thank you very much");
            //首先调用m.find 对匹配字符串进行匹配
            m.find();
            //调用appendReplacement方法,会将找到匹配字符't'之前的所有字符
            //也就是"OK,"这几个字符添加到sb中,然后在对sb中追加“你好”
            m.appendReplacement(sb,"你好");
            System.out.println(sb);//"OK,你好"
            //appendTail顾名思义也就是追加一个小尾巴,也就是将从appendReplacement
            //替换后剩余的"hank you very much"添加到sb中
            m.appendTail(sb);
            System.out.println(sb);//"OK,你好hank you very much"
        }
    }

以上就是appendReplacement和appendTail的用法

猜你喜欢

转载自blog.csdn.net/qq_16814681/article/details/81705416
今日推荐