raoul.nair
raoul.nair

Reputation: 489

Regular expression for three word seperated by two comma

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

Answers (4)

StackSlave
StackSlave

Reputation: 10627

Try this:

/^[^ ,](,\s[^ ,]){0,2}$/

Upvotes: 0

Raghavendra S
Raghavendra S

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

Almis
Almis

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

anubhava
anubhava

Reputation: 784998

You can use this regex:

/^(\w+,\s*){0,2}\w+$/gm

RegEx Demo

Or to allow special character except comma and spaces use:

/^([^\s,]+,\s*){0,2}[^\s,]+$/gm

Upvotes: 2

Related Questions