Шаблон регулярных выражений для запрета ничего, кроме запятой между - PullRequest
0 голосов
/ 28 марта 2019

Может ли кто-нибудь помочь здесь! Мне нужно регулярное выражение, где я могу получить только запятую в некоторой паре значений 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 Account|Current Account|Credit Card)[,]?)+\b

1 Ответ

0 голосов
/ 28 марта 2019

Вот, пожалуйста:

^(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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...