一道正则表达式的简单问题
把
61.54.231.245 61.54.231.245 河南省安阳市 新世纪网吧
61.54.231.246 61.54.231.246 河南省安阳市 未知地区
替换成
061.054.231.245,061.054.231.245,河南省安阳市 新世纪网吧
061.054.231.246,061.054.231.246,河南省安阳市 未知地区
每个IP地址不足3位的前面补0..谁能帮忙用正则表达式实现这个功能?
------解决方案--------------------public class Test {
public static void main(String[] args) {
String in = "61.54.231.245 61.54.231.245 河南省安阳市 新世纪网吧 ";
String[] ss1 = in.split( " ");
String out = " ";
for (int i = 0; i < 2 ; i++) {
String[] ss2 = ss1[i].split( "\\. ");
for (int n = 0; n < 4; n++) {
switch (ss2[n].length()) {
case 1:
out += "0 ";
case 2:
out += "0 ";
default:
out += ss2[n];
}
if (n < 3)
out += ". ";
}
out += " ";
}
out += ss1[2];
out += " " + ss1[3];
System.out.println(in);
System.out.println(out);
}
}
------解决方案--------------------学习了
------解决方案--------------------package com.ejoy8.utils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IPFormater {
public static void main(String[] args) {
String[] ss = new String[] { //
"61.54.231.245 61.54.231.245 河南省安阳市 新世纪网吧 ", //
"61.54.231.246 61.54.231.246 河南省安阳市 未知地区 ", //
" ", //
" ", //
};
List results = processBit(ss);
for (Iterator it = results.iterator(); it.hasNext(); System.out.println(it.next()))
;
System.out.println( "\n\n\n ");
results = processBlank((String[]) results.toArray(SS_BLANK));
for (Iterator it = results.iterator(); it.hasNext(); System.out.println(it.next()))
;
System.out.println( "\n\n\n ");
ss = format(ss);
for (int i = 0; i < ss.length; System.out.println(ss[i]), i++)
;
}
//
//
//
private static final String[] SS_BLANK = new String[] {};
private static final Pattern PATTERN_FOR_BIT = Pattern.compile( "[^\\d][\\d]{3}|[^\\d][\\d]{1,2} ");
private static final Pattern PATTERN_FOR_BLANK = Pattern.compile( "([\\d]{3})[\\s] ");
public static final String[] format(String[] ss) {
List results = processBit(ss);
results = processBlank((String[]) results.toArray(ss));
return (String[]) results.toArray(SS_BLANK);
}
private static List processBit(String[] ss) {
List results = new ArrayList();
for (int i = 0; i < ss.length; i++) {
String s = ss[i];
if (s == null)
continue;
s = " " + s;
Matcher matcher = PATTERN_FOR_BIT.matcher(s);
StringBuffer sb = null;
int start = 0;
String finalString = null;
while (matcher.find(start)) {
sb = new StringBuffer();
String wantedpart = matcher.group(0);
if (wantedpart != null) {
int key = wantedpart.length();
switch (key) {
case 2:
matcher.appendReplacement(sb, new StringBuffer(wantedpart).insert(1, "00 ").toString());