Reputation: 489
Need to match all the scenario given below
Min one word without comma
Max three words separated by two "single space+comma"( ,)
each word cannot have space in it but all special characters are allowed
sometext, sometext, sometext-->valid
sometext-->valid
sometext, sometext-->valid
sometext, sometext, sometext, -->invalid
sometext, sometext, sometext, sometext -->invalid
sometext, -->invalid
sometext sometext, sometext sometext -->invalid
tried below expression but cant validate invalid scenarios
[a-zA-Z]*(,[a-zA-Z]*){0,2}
Thanks
Upvotes: 1
Views: 81
Reputation: 627
Check this regular expression:
^([a-z]+,\s{1}){0,2}[a-z]+$
it will match exact what you mentioned example text including space also.
Upvotes: 0
Reputation: 3809
Just for fun without regex (I don't know if its faster than regex)
var examples = ['sometext, sometext, sometext',
'sometext',
'sometext, sometext',
'sometext, sometext, sometext,',
'sometext, sometext, sometext, sometext',
'sometext,',
'sometext sometext, sometext sometext'];
examples.forEach(function(example){
var splitResult = example.split(', ');
if (splitResult.length < 4 &&
splitResult.indexOf('') === -1 &&
splitResult.filter(function(x){return x.split(' ').length > 1}).length === 0 &&
splitResult.filter(function(x){return x.substr(-1) === ','}).length === 0)
console.log(example + ': valid');
else
console.log(example + ': not valid');
});
Upvotes: 0
Reputation: 784998
You can use this regex:
/^(\w+,\s*){0,2}\w+$/gm
Or to allow special character except comma and spaces use:
/^([^\s,]+,\s*){0,2}[^\s,]+$/gm
Upvotes: 2