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 ?
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.
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 ( $ ).
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.
A colon has no special meaning in Regular Expressions, it just matches a literal colon.
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.
Try:
^\w+((,\w+)+)?$
There are online regexp testers you can practice with. For example, http://regexpal.com/.
Try the next:
^[^,]+(,[^,]+)*$
You can have spaces between words and Unicode text, like:
word1 word2,áéíóú áéíúó,ñ,word3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With