把一个字符串12替换成012
字符串也可能是一位,如3替换成003
用正则表达式如何实现?
------解决方案--------------------
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExpTest {
public void test(){
String str = "3 ";
String zero = "000 ";
Pattern pattern = Pattern.compile( "[0-9]{1,3} ");
Matcher matcher = pattern.matcher(str);
if(matcher.find()){
str = str.replaceAll( "[0-9]{1,3} ", zero.substring(0,3 - str.length()) + matcher.group(0));
}
System.out.println(str);
}
public static void main(String[] args){
RegExpTest reg = new RegExpTest();
reg.test();
}
}