khaja aminul hussain
khaja aminul hussain

Reputation: 97

Regex pattern for not allowing anything except comma in between

Could anyone help here ! I need an regular expression where I can get only comma in some couple of Enum values. For example:

 Savings Account,Current Account,Credit card --> valid
 Savings Account --> valid
Savings Account,Credit Card --> valid
Credit Card,Savings Account --> valid
(Space or any special character)Savings Account --> Invalid
Savings Account(space or any special character) --> Invalid
Savings AccountCurrent Account --> Invalid (it should be separated by comma)

I have tried this below expression but It is even accepting Savings AccountCurrent Account also.

((Savings Account|Current Account|Credit Card)[,]?)+\b

Upvotes: 3

Views: 444

Answers (1)

Vaibhav Vishal
Vaibhav Vishal

Reputation: 7108

Here you go:

^(Savings Account|Current Account|Credit Card)(([,](Savings Account|Current Account|Credit Card))*)$

Explained:

^(Savings Account|Current Account|Credit Card)  # Starts with one of the Enums defined
(([,](Savings Account|Current Account|Credit Card))*)$  # Optionally contains any numbers of defined enums prefixed by `,` and ends

If don't want same string to appear twice:

^(Savings Account|Current Account|Credit Card)(,(?!\1)(Savings Account|Current Account|Credit Card))?(,(?!\3)(?!\1)(Savings Account|Current Account|Credit Card))?$

Explained:

^(Savings Account|Current Account|Credit Card)  # Capture group 1, matches one of the defined enums
(,  # start of capture group 2, checks for comma
    (?!\1)  # Negative Lookahead, makes sure it doesn't matches the result of group 1
    (Savings Account|Current Account|Credit Card)  # Capture group 3, matches one of the defined enums
)?  # end of capture group 2, make stuff inside it optional
(,  # start of capture group 4, checks for comma
    (?!\3)  # Negative Lookahead, makes sure it doesn't matches the result of group 3
    (?!\1)  # Negative Lookahead, makes sure it doesn't matches the result of group 1
    (Savings Account|Current Account|Credit Card)  # Capture group 5, matches one of the defined enums
 )?$  # end of capture group 4, make stuff inside it optional

Upvotes: 2

Related Questions