我有一个字符串,即AB1234。我正在尝试创建一种方法,我可以将字符串传递到整数的前面,以创建一个10位字符串。
一些示例:
padZero("AB1234")
返回" AB00001234"
padZero("CD001234")
返回" CD00001234"
padZero("ABCDEF858")
返回" abcdef0858"
是否有一种简单的方法可以在没有大量角案件的情况下尝试捕获?假设在方法调用之前,抓到了大于十个数字的字符串的情况。
public static void main(String[] args) {
System.out.println(padZero("abc123"));
}
public static String padZero(String init) {
Matcher matcher = Pattern.compile("\d+").matcher(init);
matcher.find();
return String.format("%s%0" + (10-matcher.start()) + "d", init.substring(0, matcher.start()), Integer.valueOf(matcher.group()));
}
以防万一您不想做假设,而在无效的输入字符串上快速失败:
private static final Pattern STRING_FORMAT = Pattern.compile("(\D+)(\d+)");
public static final String padZeros(String s) {
Matcher matcher = STRING_FORMAT.matcher(s);
if (!matcher.matches() || s.length() > 10)
throw new IllegalArgumentException("Invalid format");
char[] result = new char[10];
Arrays.fill(result, '0');
String nonDigits = matcher.group(1);
String digits = matcher.group(2);
nonDigits.getChars(0, nonDigits.length(), result, 0);
digits.getChars(0, digits.length(), result, 10 - digits.length());
return String.valueOf(result);
}
我认为最简单的是找到第一个数字,然后将足够的零插入到10位数字上:
if (text.matches("\d")) {
while (text.length() < 10) {
text = text.replaceFirst("(\d)", "0$1");
}
}