Krishnanunni P V
Krishnanunni P V

Reputation: 699

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 ?

Upvotes: 6

Views: 10793

Answers (5)

acdcjunior
acdcjunior

Reputation: 135752

Simplest form:

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

Demo here.


I need to restrict only alphabets. How can I do that ?

Use the regex (example unicode chars range included):

^[\u0400-\u04FFa-zA-Z ]+(,[\u0400-\u04FFa-zA-Z ]+)*$

Demo for this one here.

Example usage:

public static void main (String[] args) throws java.lang.Exception
{
    String regex = "^[\u0400-\u04FFa-zA-Z ]+(,[\u0400-\u04FFa-zA-Z ]+)*$";

    System.out.println("abc,xyz,pqr".matches(regex)); // true
    System.out.println("text1,text2,".matches(regex)); // false
    System.out.println("ЕЖЗ,ИЙК".matches(regex)); // true
}

Java demo.

Upvotes: 9

Bohemian
Bohemian

Reputation: 424983

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.

Upvotes: 1

Java Devil
Java Devil

Reputation: 10959

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

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

Upvotes: 0

Paul Vargas
Paul Vargas

Reputation: 42020

Try the next:

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

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

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

Upvotes: 1

Ken
Ken

Reputation: 31161

Try:

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

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

Upvotes: 2

Related Questions