Re: How do I get String.split() to do what I want?

From: Yu SONG (tips_at_mi6.gov.uk)
Date: 06/30/04


Date: Wed, 30 Jun 2004 12:35:49 +0100

Phil Hühn wrote:
> Hi, I'm using jdk 1.4.2 - last project I did in java was with jdk 1.3,
> so String.split(...) is new to me. Anyway, I've been trying to get the
> regex expression correct but not having much luck. This is probably very
> simple to everyone out there ;-)
>
> Anyway, I have something like:
>
> String myStr = "5,\'this,that\',8";
> String parts[] = myStr.split(",");
>
> Of course I get a split at ALL the commas (i.e it sees the comma within
> the quotes) so I get 4 parts:
>
> "5", "'this", "that'", "8"
>
> But I want any quoted string left intact, ideally:
>
> "5", "'this,that'", "8"
>
> (And I'll get rid of the single quote marks).
> So pretty easy... what's the correct regex split argument to do this?
>
> TIA

We have to look at the pattern of these strings,

is it always in the form of "digit, 'abc', digit"?

Assume there is no space in 'abc', you can split the "myStr" string into

"5", "this,that", "8",

using the following code:

        String myStr = "5,\'this,that\',8";

        //spilt the string using "'", as you want to get rid of it
        String parts[] = myStr.split("'");

        //for output
        StringBuffer output = new StringBuffer();

        for (int i = 0; i < parts.length; i++) {
                //replace ',' for space to trim
                parts[i] = parts[i].replace(',', ' ').trim();

                //replace back
                parts[i] = parts[i].replace(' ', ',');

                //for output
                output.append('\"');
                output.append(parts[i]);
                output.append("\", ");
        }
        //output
        System.out.println(output.toString());

-- 
Song
/* E-mail.c */
#define User            "Yu.Song"
#define At              '@'
#define Warwick         "warwick.ac.uk"
int main() {
printf("Yu Song's E-mail: %s%c%s", User, At, Warwick);
return 0;}
Further Info. :   http://www.dcs.warwick.ac.uk/~esubbn/
_______________________________________________________