java - Replace a substring by a changing replacement string -
i'm trying write small program detect comments in code file, , tag them index-tag, meaning tag increasing value.
example input:
method int foo (int y) { int temp; // first comment temp = 63; // second comment // third comment } should 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 following code:
string prefix, suffix; string pattern = "(//.*)"; pattern r = pattern.compile(pattern); matcher m = r.matcher(filetext); int = 0; suffix = "</tag>"; while (m.find()) { prefix = "<tag_" + + ">"; system.out.println(m.replaceall(prefix + m.group() + suffix)); i++; } the output 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> }
to replace occurrences of detected patterns, should use matcher#appendreplacement method fills stringbuffer:
stringbuffer sb = new stringbuffer(); while (m.find()) { prefix = "<tag_" + + ">"; m.appendreplacement(sb, prefix + m.group() + suffix); i++; } m.appendtail(sb); // append rest of contents the reason replaceall wrong replacement have matcher scan whole string replace every matched pattern <tag_0>...</tag>. in effect, loop execute once.
Comments
Post a Comment