'Regex pattern accepting comma separated values

I need a regex pattern that accepts only comma separated values for an input field.

For example: abc,xyz,pqr. It should reject values like: , ,sample text1,text2,

I also need to accept semicolon separated values also. Can anyone suggest a regex pattern for this ?



Solution 1:[1]

Try:

^\w+((,\w+)+)?$

There are online regexp testers you can practice with. For example, http://regexpal.com/.

Solution 2:[2]

Try the next:

^[^,]+(,[^,]+)*$

You can have spaces between words and Unicode text, like:

word1 word2,áéíóú áéíúó,ñ,word3

Solution 3:[3]

The simplest regex that works is:

^\w+(,\w+)*$

And here it is as a method:

public static boolean isCsv(String csv) {
    return csv.matches("\\w+(,\\w+)*");
}

Note that String.matches() doesn't need the start or end regex (^ and $); they are implied with this method, because the entire input must be matched to return true.

Solution 4:[4]

I think you want this, based on your comment only wanting alphabets (I assume you mean letters)

^[A-Za-z]+(,[A-Za-z]+)*$

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SK9
Solution 2 Paul Vargas
Solution 3
Solution 4 Java Devil