Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex pattern accepting comma or semicolon separated values

Tags:

java

regex

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 ?

like image 851
Krishnanunni P V Avatar asked Jun 26 '13 04:06

Krishnanunni P V


People also ask

Is semicolon special in regex?

Semicolon is not in RegEx standard escape characters. It can be used normally in regular expressions, but it has a different function in HES so it cannot be used in expressions. As a workaround, use the regular expression standard of ASCII.

How do you avoid commas in regex?

So, this regular expression means "At the start of the string ( ^ ), match any character that's not a comma ( [^,] ) one or more times ( + ) until we reach the end of the string ( $ ).

What is the regex for comma?

In regex, there are basically two types of characters: Regular characters, or literal characters, which means that the character is what it looks like. The letter "a" is simply the letter "a". A comma "," is simply a comma and has no special meaning.

How do you use a colon in regex?

A colon has no special meaning in Regular Expressions, it just matches a literal colon.


3 Answers

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.

like image 136
acdcjunior Avatar answered Nov 13 '22 16:11

acdcjunior


Try:

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

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

like image 32
SK9 Avatar answered Nov 13 '22 15:11

SK9


Try the next:

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

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

word1 word2,áéíóú áéíúó,ñ,word3
like image 31
Paul Vargas Avatar answered Nov 13 '22 16:11

Paul Vargas