6

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
  • 607,720
  • 39
  • 448
  • 563
Krishnanunni P V
  • 689
  • 5
  • 18
  • 32

5 Answers5

9

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
  • 132,397
  • 37
  • 331
  • 304
2

Try:

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

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

Ken
  • 30,811
  • 34
  • 116
  • 155
1

Try the next:

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

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

word1 word2,áéíóú áéíúó,ñ,word3
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
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
  • 412,405
  • 93
  • 575
  • 722
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,629
  • 7
  • 33
  • 48