我有这样的示例数据:
<o:-200> Text1
<o:7> Text2
<o:218> Text3
<o:325> Text4
我想做的事:
1) 从标签中获取数字(-200、7等) 2) 给这个数字加上值(例如 + 100) 3)更改后的数字替换为整个标签
输出:
-100 Text1
107 Text2
318 Text3
425 Text4
这是我的代码:
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);
但我的输出是:
-100 Text1
107 Text2
318 Text3
425
但我想要全文。 ReplaceAll 不起作用(更改找到的第一个值的所有标签)。
我怎样才能做到这一点?
最佳答案
查看该方法的文档Matcher.appendReplacement
。它包含一个示例,清楚地显示您缺少一行:
while(...) {...}
m.appendTail(s1); // <- this one
关于java - 通过正则表达式切割文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28173148/