首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

正则 将引号外的多个空格替换成一个空格

2013-03-17 
正则 将引号外的多个空格替换成1个空格如:将引号外的多个空格替换成1个空格a bcdefg- a b cdef ga bc

正则 将引号外的多个空格替换成1个空格
如:
将引号外的多个空格替换成1个空格
a b   c'   d  ef'   g   -> a b c'   d  ef' g
a b   c'  '  d  ef'   g -> a b c'  '  d  ef' g

[解决办法]
用一个正则替换整个字符串比较困难。
其实只要替换用"'"分割后的首尾两个字符串就可以了


public class Test7 {
public static void main(String[] args) {
String str1 = "a b   c'   d  ef'   g";
String str2 = "a b   c'  '  d  ef'   g";
String str3 = "a   a  s '2''3 '''' ' g''  sssd'''";
System.out.println(formatStr(str1));
System.out.println(formatStr(str2));
System.out.println(formatStr(str3));
}

static String formatStr(String src) {
final String flag = "'";
boolean isLastFlag = false;
// 不包含flag直接替换
if (!src.contains(flag)) {
return src.replaceAll("\\s{2,}", " ");
}
// 以flag分割数组,只有第一个和最后一个元素需要替换
// 考虑字符串最后一个字符恰好是flag的情况
if (src.endsWith(flag)) {
src += " ";
isLastFlag = true;
}
final String[] arr = src.split(flag);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; ++i) {
if (i == 0) {
sb.append(arr[i].replaceAll("\\s{2,}", " "));
} else if (i == arr.length - 1) {
if (!isLastFlag) {
sb.append(flag + arr[i].replaceAll("\\s{2,}", " "));
} else {


sb.append(flag);
}
} else {
sb.append(flag + arr[i]);
}
}
return sb.toString();
}
}


[解决办法]
String s = "a      '     b' '    c      '";
Pattern p = Pattern.compile("\\'(\\s{2,})");
Matcher m = p.matcher(s);
while(m.find())
{
s=s.replace(m.group(1), " ");
p = Pattern.compile("\\'(\\s{2,})");
m = p.matcher(s);

}
p = Pattern.compile("(\\s{2,})\\'");
m = p.matcher(s);
while(m.find())
{
s=s.replace(m.group(1), " ");
p = Pattern.compile("(\\s{2,})\\'");
m = p.matcher(s);
}
System.out.println(s);



这几行代码貌似可以满足你的需求,你看看吧!如果有不足之处,望斧正。

热点排行