用于根据搜索字符串插入文本的字符串正则表达式

String Regex for insert text based on searchstring

我有以下 class.

  public class TestStringRegex {

    public static void main(String[] args) {
        StringBuilder text = new StringBuilder("KALAKA");
        String wordToFind = "KA";
        Pattern word = Pattern.compile(wordToFind);
        Matcher match = word.matcher(text);

        while (match.find()) {
            System.out.println(match.end());
            text=text.insert(match.end(),"INSERT");

        }
        System.out.println(text);


    }

期望输出为 KAINSERTLAKAINSERT。 但是得到 KAINSERTLAKA。 matcher/insert 是否适用于输入文本的长度?如何获得所需的输出。

如果您想使用 matcher 来实现,请使用 int 的重载方法,即 matcher.find(index)。出于某种原因 mathcher.find() 没有按照文档中给出的那样工作。如果你很好奇,你需要调试代码。

像下面这样说

int end = 0;
while (match.find(end)) {
    end = match.end();
    System.out.println(end);
    text=text.insert(end,"INSERT");
}

更好的方法是

public static void main(String[] args) {
    System.out.println("KALAKA".replaceAll("KA", "[=11=]INSERT"));
}

这就是您需要编写的所有代码。

使用 matcher.find(int startIndex) 代替 find()。并在每次比赛后更新 startIndex。完整代码:

public static void main(String[] args) {
        StringBuilder text = new StringBuilder("KALAKA");
        String wordToFind = "KA";
        Pattern word = Pattern.compile(wordToFind);
        Matcher match = word.matcher(text);

        int findIndex = 0;
        while (match.find(findIndex)) {
            int end = match.end();
            findIndex = end;
            text = text.insert(end, "INSERT");

        }
        System.out.println(text);

    }

每个下一个 find() 都从上一个匹配项的末尾开始

这很好..!!!

public static void main(String[] args) {
    StringBuilder text = new StringBuilder("KALAKA");
    String wordToFind = "KA";
    Pattern word = Pattern.compile(wordToFind);
    Matcher match = word.matcher(text);
    int end = 0;
    while (match.find(end)) {
        end = match.end();
        text=text.insert(match.end(),"INSERT");
    }
    System.out.println(text);
}