1

I'm trying to go through a string and replace all instances of a regex-matching string. For some reason when I use if then it will work and replace just one string instance of a regex-match. When I change the if to while then it does some weird replacement over itself and makes a mess on the first regex-matching string while not even touching the others...

        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();
        }
4

3 回答 3

3

除了 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);
}
于 2012-12-16T15:00:42.060 回答
1

不确定你到底遇到了什么问题,但也许这个例子会有所帮助:

我想在句子中更改名称,例如:

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

我们可以在类中的appendReplacementappendTail方法的帮助下做到这一点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.
于 2012-12-16T15:11:15.020 回答
0

如果 createRef(match) 返回一个与 (end - start) 长度不同的字符串,那么您在 docToProcess.substring(start, end) 中使用的索引可能会重叠。

于 2012-12-16T14:47:10.340 回答