Java 对于这个例子,什么是合适的正则表达式?

Java 对于这个例子,什么是合适的正则表达式?,java,regex,Java,Regex,java中的哪个正则表达式可以进行这些转换 "1.54.0.21" to "01540021" 或 我需要将替换为0,将替换为。替换为。公共字符串getToken(String elem){ 返回值(元素大小()==1)?(“0”+元素):元素; } 字符串[]a=“1.54.0.21”。拆分(\\”; 字符串o=”“,e; int i=0,len=a.size(); 对于(i=0;i

java中的哪个正则表达式可以进行这些转换

"1.54.0.21" to "01540021"

我需要将
替换为
0
,将
替换为
替换为

公共字符串getToken(String elem){
返回值(元素大小()==1)?(“0”+元素):元素;
}
字符串[]a=“1.54.0.21”。拆分(\\”;
字符串o=”“,e;
int i=0,len=a.size();
对于(i=0;i
您可以尝试以下方法:

StringBuilder output = new StringBuilder(8);
String input = "1.54.0.21";
Pattern p = Pattern.compile("\\d+");
Matcher matcher = p.matcher(input);
while (matcher.find()) {
    String group = matcher.group();
    if (group.length() < 2) {
        output.append("0");
    }
    output.append(group);
}

System.out.println(input);
System.out.println(output);

正则表达式的唯一功能是匹配字符串(或多行字符串)中的特定字符模式。 正则表达式可以在查找和替换模式中使用,但只能查找您感兴趣的字符串。找到它们后,一个Split()、Remove()、Replace()函数将更好地实现它的目的

I recommend you : http://gskinner.com/RegExr/  
这是一个在线工具,用于将字符串与正则表达式匹配,以及学习模式

不带正则表达式:


String#replaceAll(“\\.”,“”)有什么问题?不,我需要用
0
替换
,用
替换
@mad程序员注意额外的0。啊,所以他们在填充:PSo,
字符串。拆分
。。。
StringBuilder output = new StringBuilder(8);
String input = "1.54.0.21";
Pattern p = Pattern.compile("\\d+");
Matcher matcher = p.matcher(input);
while (matcher.find()) {
    String group = matcher.group();
    if (group.length() < 2) {
        output.append("0");
    }
    output.append(group);
}

System.out.println(input);
System.out.println(output);
1.54.0.21
01540021
I recommend you : http://gskinner.com/RegExr/  
public static void main(String args[])
{
    String str1 = "33.5.9.6";
    String str2 = "1.54.0.21";
    System.out.println(transform(str1));
    System.out.println(transform(str2));
}

private static String transform(String str){
    String[] splitted = str.split("\\.");
    StringBuilder build = new StringBuilder();
    for(String s : splitted){
        build.append(String.format("%02d", Integer.parseInt(s)));
    }
    return build.toString();
}