Saturday, November 5, 2011

Split a string on commas and whitespaces

package au.com.d2klry.string;

public class Tokenizer {

    public static void main(String args[]){
        String fullNameWithCommaNSpace = "Lastname,  FirstName";
        String fullNameWithComma = "Lastname,FirstName";
        String fullNameWithSpace = "Lastname FirstName";

        String regExp = "[,\\s]+";
    
        for (String token : fullNameWithCommaNSpace.split(regExp))
            System.out.println("FullNameWithCommaNSpace Token : " + token);

        for (String token : fullNameWithComma.split(regExp))
            System.out.println("FullNameWithComma Token : " + token);

        for (String token : fullNameWithSpace.split(regExp))
            System.out.println("FullNameWithSpace Token : " + token);
    }

}

No comments:

Post a Comment