任何人都可以在这里帮忙! 我需要一个正则表达式,在其中我只能在几个Enum值中使用逗号。 例如:
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)
我已经尝试过以下表达式,但它甚至也接受Savings AccountCurrent Account。
((Savings Account|Current Account|Credit Card)[,]?)+\b
答案 0 :(得分:0)
您在这里:
^(Savings Account|Current Account|Credit Card)(([,](Savings Account|Current Account|Credit Card))*)$
解释:
^(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
如果不想让相同的字符串出现两次:
^(Savings Account|Current Account|Credit Card)(,(?!\1)(Savings Account|Current Account|Credit Card))?(,(?!\3)(?!\1)(Savings Account|Current Account|Credit Card))?$
解释:
^(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