5

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 ?

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
Krishnanunni P V
  • 629
  • 4
  • 17
  • 31

5 Answers5

8

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.

acdcjunior
  • 124,334
  • 35
  • 321
  • 293
2

Try:

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

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

SK9
  • 30,156
  • 34
  • 113
  • 154
1

Try the next:

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

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

word1 word2,áéíóú áéíúó,ñ,word3
Paul Vargas
  • 40,346
  • 15
  • 98
  • 144
1

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.

Bohemian
  • 389,931
  • 88
  • 552
  • 692
0

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

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

Java Devil
  • 10,281
  • 7
  • 31
  • 46