日期:2014-05-20 浏览次数:20858 次
Map<String, String> map = new HashMap<String, String>();
Pattern quotRegex = Pattern.compile("'.*?'");
Matcher matcher = quotRegex.matcher(str);
StringBuffer buff = new StringBuffer();
while (matcher.find()) {
String key = "__PLACEHOLDER__" + map.size();
String value = matcher.group();
map.put(key, value);
matcher.appendReplacement(buff, key);
}
matcher.appendTail(buff);
// 以上内容将配对的引号内的东西,存为一个不太容易出现的占位符
// 以下将连续的空白符号替换掉,此时,已经不会有引号内的连续空白干扰正则
StringBuffer buff2 = new StringBuffer();
String str2 = buff.toString().replaceAll("\\s{2,}", " ");
Pattern placeholderRegex = Pattern.compile("__PLACEHOLDER__\\d+");
Matcher placeholderMatcher = placeholderRegex.matcher(str2);
while (placeholderMatcher.find()) {
String key = placeholderMatcher.group();
String value = map.get(key);
placeholderMatcher.appendReplacement(buff2, value);
}
placeholderMatcher.appendTail(buff2);
return buff2.toString();
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 {