Ikshvak
Ikshvak

Reputation: 205

regex for comma separated values

I am new to write regular expressions so please help.

I want to match this pattern (in Java):

"ABC",010,00,"123",0,"time","time",01,00, 10,    10,88,217," ",," "

the data I get will always be in the above format with 16 values. But the format will never change.

I am not looking for parsing as this can be parsed by java split too. I will have large chunks of these data so want to capture the first 16 data points and match with this pattern to check if I received it correctly else ignore.

so far I have only tried this regex:

^(\".\"),.,(\".\"),.,(\".\"),(\".\"),.,.,.,.,.,.,(\".\"),.,(\".\")$

I am still in the process of building it.

I just need to match the pattern from a given pool. I take first 16data points and try to see if it matches this pattern else ignore.

Thanks!!

Upvotes: 1

Views: 12447

Answers (2)

Dinesh Lomte
Dinesh Lomte

Reputation: 609

Please find in the below code comprising comma separated evaluation for String, Number and Decimal.

 public static void commaSeparatedStrings() {       
    String value = "'It\\'s my world', 'Hello World', 'What\\'s up', 'It\\'s just what I expected.'";

    if (value.matches("'([^\'\\\\]*(?:\\\\.[^\'\\\\])*)[\\w\\s,\\.]+'(((,)|(,\\s))'([^\'\\\\]*(?:\\\\.[^\'\\\\])*)[\\w\\s,\\.]+')*")) {
        System.out.println("Valid...");
    } else {
        System.out.println("Invalid...");
    }
}

/**
 * 
 */
public static void commaSeparatedDecimals() {
    String value = "-111.00, 22111.00, -1.00";
    // "\\d+([,]|[,\\s]\\d+)*"
    if (value.matches(
            "^([-]?)\\d+\\.\\d{1,10}?(((,)|(,\\s))([-]?)\\d+\\.\\d{1,10}?)*")) {
        System.out.println("Valid...");
    } else {
        System.out.println("Invalid...");
    }
}

/**
 * 
 */
public static void commaSeparatedNumbers() {
    String value = "-11, 22, -31";      
    if (value.matches("^([-]?)\\d+(((,)|(,\\s))([-]?)\\d+)*")) {
        System.out.println("Valid...");
    } else {
        System.out.println("Invalid...");
    }
}

Upvotes: 1

tazer84
tazer84

Reputation: 1823

This should do the trick. Keep in mind that he doesn't care what order the data points occur in (ie. they could all be strings or all numbers).

(\s?("[\w\s]*"|\d*)\s?(,|$)){16}

You can try it out here.

Upvotes: 6

Related Questions