Reputation: 533
I have sample data like this:
<o:-200> Text1
<o:7> Text2
<o:218> Text3
<o:325> Text4
What I want to do:
1) Get number from tag (-200, 7, etc.) 2) Add value to this number (e.x. + 100) 3) Changed number replace with whole tag
Output:
-100 Text1
107 Text2
318 Text3
425 Text4
That's my code:
String s;
Pattern p1 = Pattern.compile("<o:(-?[0-9]+)>");
Matcher m = p1.matcher("<o:-200> ABC\n<o:7> ASDQWE\n<o:218> 12345.67\n<o:325> ASDFGD asdfsdf\n");
StringBuffer s1 = new StringBuffer();
while (m.find()){
m.appendReplacement(s1, String.valueOf(100 + Integer.parseInt(m.group(1))));
}
s = s1.toString().replaceAll("<o:\\b(\\d+)\\b>", "$1" );
System.out.println(s);
But my output is:
-100 Text1
107 Text2
318 Text3
425
But I want whole text. ReplaceAll doesn't work (changing all tags with 1st value found).
How can I do that?
Upvotes: 0
Views: 62
Reputation: 20608
Look into the documentation of the method Matcher.appendReplacement
. It contains an example that clearly shows you one line missing:
while(...) {...}
m.appendTail(s1); // <- this one
Upvotes: 4