更换虽然型样(Replace While Pattern is Found)

2019-08-04 04:51发布

我试图去通过串并更换正则表达式匹配字符串的所有实例。 出于某种原因,当我使用if然后它会工作,并更换正则表达式匹配的只是一个字符串实例。 当我改变了ifwhile则它在本身的一些奇怪的更换,使得第一正则表达式匹配字符串的一塌糊涂,而即使不触及其他...

        pattern = Pattern.compile(regex);
        matcher = pattern.matcher(docToProcess);
        while (matcher.find()) {
            start = matcher.start();
            end = matcher.end();
            match = docToProcess.substring(start, end);
            stringBuilder.replace(start, end, createRef(match));
            docToProcess = stringBuilder.toString();
        }

Answer 1:

除了从sysouts我只加了最后的分配。 看看是否有帮助:

// your snippet:    
pattern = Pattern.compile(regex);
matcher = pattern.matcher(docToProcess);
while (matcher.find()) {
    start = matcher.start();
    end = matcher.end();
    match = docToProcess.substring(start, end);
    String rep = createRef(match);
    stringBuilder.replace(start, end, rep);
    docToProcess = stringBuilder.toString();
    // my addition:
    System.out.println("Found:         '" + matcher.group() + "'");
    System.out.println("Replacing with: '" + rep + "'");
    System.out.println(" --> " + docToProcess);
    matcher = pattern.matcher(docToProcess);
}


Answer 2:

不知道到底你得到了什么问题,但也许这个例子有点帮助:

我想在这样的句子来更改名称:

  • 杰克 - >阿尔伯特
  • 阿尔伯特 - >保罗
  • 保罗 - >杰克

我们可以用一点帮助做到这一点appendReplacement和appendTail从方法Matcher

//this method can use Map<String,String>, or maybe even be replaced with Map.get(key)
static String getReplacement(String name) { 
    if ("Jack".equals(name))
        return "Albert";
    else if ("Albert".equals(name))
        return "Paul";
    else
        return "Jack";
}

public static void main(String[] args) {

    String sentence = "Jack and Albert are goint to see Paul. Jack is tall, " +
            "Albert small and Paul is not in home.";

    Matcher m = Pattern.compile("Jack|Albert|Paul").matcher(sentence);

    StringBuffer sb = new StringBuffer();

    while (m.find()) {
        m.appendReplacement(sb, getReplacement(m.group()));
    }
    m.appendTail(sb);

    System.out.println(sb);
}

输出:

Albert and Paul are goint to see Jack. Albert is tall, Paul small and Jack is not in home.


Answer 3:

如果createRef(匹配)返回一个字符串这是不相同的长度(结束 - 开始),则使用的是在docToProcess.substring(开始,结束)的索引将潜在地重叠。



文章来源: Replace While Pattern is Found