【发布时间】:2020-12-08 14:22:39
【问题描述】:
如何在 python re 中编写正则表达式,其中模式为: 3个英文字母后跟一个逗号
例子:
string_var = "AAA, BBB, CCC" # follows the pattern
string_var = "AAA, BBBB, CCC, DDD" # does not follow the pattern
【问题讨论】:
如何在 python re 中编写正则表达式,其中模式为: 3个英文字母后跟一个逗号
例子:
string_var = "AAA, BBB, CCC" # follows the pattern
string_var = "AAA, BBBB, CCC, DDD" # does not follow the pattern
【问题讨论】:
如果您只想检查字符串是否匹配,请使用^[A-Za-z]{3}, [A-Za-z]{3}, [A-Za-z]{3}$ (https://regexr.com/5i22s)。这对于“AAA, BBB, CCC”是正确的,但对于像“test asf, cat, dog”这样的查找匹配没有用。
^ Start of string
[A-Za-z] Alphabet characters
{3} 3 alphabet characters
, A comma followed by a space
...
$ End of string
【讨论】:
试试这个
^([a-zA-Z]{3},\s){2}[a-zA-Z]{3}$
或将其与re.I 标志一起使用
^([a-z]{3},\s){2}[a-z]{3}$
【讨论】: