首页 > 解决方案 > Regex comma delimited string with specific characters

问题描述

I'm looking for a pattern that will match each character in a comma delimited string and make sure it is one of a specific set of characters

Specific set of characters = A, B, C

I'm pretty new to regex so it would be nice if you could break down how this works as well please :)

Example

The following strings should match
A
A,B
A,B,C,B,A,B,C

The following strings should not match
D
A,D
A,B,C,B,B,A,D

标签: regex

解决方案


如果您只想匹配整个字符串(而不是其中的任何组),您可以简单地匹配包含任意数量的指定字符和逗号的字符串:

^[ABC][ABC,]*$

编辑:如果您需要确保不匹配双字母(例如,A,B,CC, A 不应该匹配),那么您可以对该特定模式进行分组:

^[ABC](,[ABC])*$

推荐阅读