Regex 使用逗号(或空格)重复的模式的正则表达式
我想验证包含由逗号或空格分隔的特定单词列表的短语。单词列表可以是Regex 使用逗号(或空格)重复的模式的正则表达式,regex,Regex,我想验证包含由逗号或空格分隔的特定单词列表的短语。单词列表可以是[A-E]\d和(ST | ST)\d(作为正则表达式)。因此,一个有效的短语应该是: A1、a2、B1、ST1、st3、c3、e4、st6 而A11、G2、stt3则不会 我想出了这个正则表达式: ^([A-E|a-e])?(?(1)\d|(?:ST|st)\d)(?:[\s,]+([A-E|a-e])?(?(2)\d|(ST|st)\d))*$ 但它并不总是成功的。当b3,st2,a3,st3成功时,b3,st2,a3,st3
[A-E]\d
和(ST | ST)\d
(作为正则表达式)。因此,一个有效的短语应该是:
A1、a2、B1、ST1、st3、c3、e4、st6
而A11、G2、stt3则不会
我想出了这个正则表达式:
^([A-E|a-e])?(?(1)\d|(?:ST|st)\d)(?:[\s,]+([A-E|a-e])?(?(2)\d|(ST|st)\d))*$
但它并不总是成功的。当b3,st2,a3,st3
成功时,b3,st2,a3,st3
失败
有什么帮助吗?您可以使用以下模式和i
标志进行不区分大小写的匹配:
^(?[A-E]| ST)\d(?:\s*,\s*(?:[A-E]| ST)\d)+$
详细信息:
^ # Beginning of the string/line.
(?:[A-E]|ST) # Match either a single letter between 'A and 'E' or 'ST'.
\d # Match a single digit.
(?: # Beginning of a non-capturing group.
\s*,\s* # Match a single comma surrounded by optional whitespace characters.
(?:[A-E]|ST)\d # Either a letter between 'A and 'E' or 'ST' followed by a digit.
) # End of the non-capturing group.
+ # Match the previous group between one and unlimited times.
$ # End of the string/line.
# demo https://regex101.com/r/hi6eWn/1
# ^\s*(?:[A-Ea-e]|ST|st)\d(?:\s*,\s*(?:[A-Ea-e]|ST|st)\d)*\s*$
^ # BOL
\s* # wsp, opt
(?: [A-Ea-e] | ST | st ) # The letter part, core word
\d # The digit part, core word
(?: # Trailing CSV core parts, opt
\s* , \s*
(?: [A-Ea-e] | ST | st )
\d
)*
\s* # wsp, opt
$ # EOL