[英]String.replaceAll variation
Is there a quick way to replace all of some pattern occurrences with data derived from the matched pattern? 有没有一种快速的方法可以用匹配的模式派生的数据替换所有模式出现的情况?
For example, if I wanted to replace all occurrences of a number within a string with the same number padded to fixed length with 0s. 例如,如果我想用相同的数字替换字符串中所有出现的数字,并用0填充到固定长度。
In this case if the length is 4, then ab3cd5
would become ab0003cd0005
. 在这种情况下,如果长度为4,则
ab3cd5
将变为ab0003cd0005
。
My idea was using a StringBuilder and 2 patterns: one would get all numbers and the other would get everything that is not a number, and appending the matches to the builder by the index the matches were found. 我的想法是使用StringBuilder和2种模式:一种将获取所有数字,另一种将获取非数字的所有内容,然后将匹配项附加到生成器,并找到匹配项的索引。
I think there might be something simpler. 我认为可能更简单一些。
You can probably achieve what you're after using appendReplacement
and appendTail
, something like this: 使用
appendReplacement
和appendTail
,您可能可以实现自己的appendTail
,如下所示:
import java.util.regex.Pattern; 导入java.util.regex.Pattern; import java.util.regex.Matcher;
导入java.util.regex.Matcher;
String REGEX = "(\\d+)";
String INPUT = "abc3def45";
NumberFormat formatter = new DecimalFormat("0000");
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // get a matcher object
StringBuffer sb = new StringBuffer();
while(m.find()){
m.appendReplacement(sb,formatter.format(Integer.parseInt(m.group(1))));
}
m.appendTail(sb);
String result = sb.toString();
If you know exactly how many zeros you want to pad before any single number, then something like this should work: 如果您确切知道要在任何单个数字前填充多少个零,那么应该可以执行以下操作:
String text = "ab3cd5";
text = text.replaceAll("\\d","0000$0");
System.out.println(text);
Otherwise: 除此以外:
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
StringBuffer result = new StringBuffer();
while(matcher.find()){
matcher.appendReplacement(result, String.format("%04d", Integer.parseInt(matcher.group())));
}
matcher.appendTail(result);
System.out.println(result);
The format %04d
means: an integer, padded by zero up to a length of 4. 格式
%04d
表示:一个整数,用零填充,直到长度为4。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.