Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a substring by a changing replacement string

I'm trying to write a small program that detect comments in a code file, and tag them by a index-tag, meaning a tag with an increasing value.
For example this input:

method int foo (int y) { 
    int temp; // FIRST COMMENT
    temp = 63; // SECOND COMMENT
    // THIRD COMMENT
}

should be change to:

method int foo (int y) { 
    int temp; <TAG_0>// FIRST COMMENT</TAG>
    temp = 63; <TAG_1>// SECOND COMMENT</TAG>
    <TAG_2>// THIRD COMMENT</TAG>
}

I tried the following code:

    String prefix, suffix;
    String pattern = "(//.*)";

    Pattern r = Pattern.compile(pattern);
    Matcher m = r.matcher(fileText);

    int i = 0;
    suffix = "</TAG>";

    while (m.find()) {
        prefix = "<TAG_" + i + ">";
        System.out.println(m.replaceAll(prefix + m.group() + suffix));
        i++;
    }

The output for the above code is:

method int foo (int y) { 
    int temp; <TAG_0>// FIRST COMMENT</TAG>
    temp = 63; <TAG_0>// SECOND COMMENT</TAG>
    <TAG_0>// THIRD COMMENT</TAG>
}
like image 559
Presen Avatar asked Jul 18 '26 06:07

Presen


1 Answers

To replace occurrences of detected patterns, you should use the Matcher#appendReplacement method which fills a StringBuffer:

StringBuffer sb = new StringBuffer();
while (m.find()) {
    prefix = "<TAG_" + i + ">";
    m.appendReplacement(sb, prefix + m.group() + suffix);
    i++;
}
m.appendTail(sb); // append the rest of the contents

The reason replaceAll will do the wrong replacement is that it will have the Matcher scan the whole string to replace every matched pattern with <TAG_0>...</TAG>. In effect, the loop would only execute once.

like image 175
M A Avatar answered Jul 20 '26 19:07

M A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!