Question

How can I remove all whitespaces that are outside "" on a String? For example:

0507 ? "Y e a" : "No"

Should return:

0507?"Y e a":"No"

Thank you.

Was it helpful?

Solution

try

    String s = "0507 ? \"Y e a\" : \"No\"".replaceAll(" +([?:]) +", "$1");
    System.out.println(s);

prints

0507?"Y e a":"No"

OTHER TIPS

OR try StringTokenizer : Read The tokenizer uses the default delimiter set, which is " \t\n\r\f": the space character, the tab character, the newline character, the carriage-return character, and the form-feed character.

    StringTokenizer tok=new StringTokenizer(yourString);
    String temp="";

    while(tok.hasMoreElements()){
        temp=temp+tok.nextElement();
    }

    System.out.println("temp"+temp);

-you can split by " using st.split() function

-then apply st.replaceAll("\s","") only on the even indexes of array

-then concate all elements of array using various utilites like Apache Commons lang StringUtils.join(

eg:

Original String - 0507 ? "Y e a" : "No"

After split with " ..... {0507 ? ,Y e a, : ,No}

Apply st.replaceAll("\s","") on even indexes of array .... {0507? ,Y e a,:,No}

Concate using StringUtils.join(s, "\"")...... 0507? "Y e a":"No"

Sample Code:

    String input="0507 ? \"Y e a\" : \"No\"";
    String[] inputParts = input.split("\"");

    int i = 0;
    while(i< inputParts.length)
    {
        inputParts[i]=inputParts[i].replaceAll("\\s", "");
        i+=2;
    }

    String output = StringUtils.join(inputParts, "\"");

This code

static Pattern groups = Pattern.compile("([^\\\"])+|(\\\"[^\\\"]*\\\")");
public static void main(String[] args) {
    String test1="0507 ? \"Y e a\" : \"No\"";
    System.out.println(replaceOutsideSpace(test1));
    String test2="0507 ?cc \"Y e a\" :bb \"No\"";
    System.out.println(replaceOutsideSpace(test2));
    String test3="text text  text   text \"Y e a\" :bb \"No\"  \"\"";
    System.out.println(replaceOutsideSpace(test3));
    String test4="text text  text   text \"Y e a\" :bb \"No\"  \"\" gaga gag   ga  end";
    System.out.println(replaceOutsideSpace(test4));
}
public static String replaceOutsideSpace(String text){
    Matcher m = groupsMatcher(text);
    StringBuffer sb = new StringBuffer(text.length());
    while(m.find()){
        String g0=m.group(0);
        if(g0.indexOf('"')==-1){g0=g0.replaceAll(" ", "");}
        sb.append(g0);
    }
    return sb.toString();
}
private synchronized static Matcher groupsMatcher(String text)
{return groups.matcher(text);}   

prints

0507?"Y e a":"No"
0507?cc"Y e a":bb"No"
texttexttexttext"Y e a":bb"No"""
texttexttexttext"Y e a":bb"No"""gagagaggaend
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top