用逗号分割字符串但不在%后面

时间:2014-07-23 00:25:11

标签: java split

我想用逗号分割一个字符串,而不是用%后面的逗号(无论键#,\,......等)。 同时打印出来"%"在输出字符串中。

示例1:

String record="AA BBB %,CCC, 23, Female";
String[] outputString=record.split("[,[^%,]]");

我想要的输出格式:

AA BBB ,CCC
23
Female

示例2:

String record="AA BBB %,CCC\%, 23, Female";
String[] outputString=record.split("[,[^%,]]");

我想要的输出格式:

AA BBB ,CCC%
23
Female

2 个答案:

答案 0 :(得分:0)

String record = "Su Mon %,Zaw, 23, Female";
String[] outputString = new String[20];
String current = "";
String previous = "";
int index = 0;
int start = 0;
int indexOfString = 0;

Pattern keywords = Pattern.compile("\%");//put your pattern here
while(index < record.length()) {
    current = record.substring(index,index);
    if(index > 0) {
        previous = record.substring(index-1, index);
    }
    if(current.equals(",") && !keywords.matcher(previous).matches()) {
        outputString[indexOfString] = record.substring(start, index);
        start = index;//update start to next index position
        indexOfString++;
    }
    index++;
}

答案 1 :(得分:0)

使用负面的背后隐藏

String[] outputString = record.split("(?<!%),\\s*");
for (int i = 0; i < outputString.length; i++)
    outputString[i] = outputString[i].replaceAll("%,", ",");

(?<!%)返回仅在匹配的部分之前没有%时才会发生匹配 \\s*与逗号后的空格匹配,这样您就不会在字符串的开头有空格。
for循环会导致所有%,被文字,替换。