我试图编写一个正则表达式来匹配包含x、y或z的字符串,但其中只能有1-2个
例如:
有效字符串=xxxx, xxxyyyy, xyxyx, zyzzzyyy, xzzzxx
无效字符串=xyz, xxxyyyyz, zxzyy
我最初是这样写的
regex = re.compile("((x*y*)*)|((x*z*)*)|(y*z*)*)")
我在这里的逻辑是,它首先用xy、xz、yz测试字符串。但不幸的是,这并不奏效。它适用于我的第一个测试字符串xyxyx,但对于我的第二个字符串zyzyzyzy,它不匹配。我是否以错误的方式使用垂直“或”线
我不太清楚你是如何得到你所得到的,但是如果你想匹配一个序列(只有
x
和y
)或者(只有x
和z
)或者(只有y
和z
),你可以使用这样的表达式:字符类(方括号)是指定“这些字符中的任何一个”的方便方法。因此
[xy]*
表示“仅由x和y字符组成的任意长度的序列”^
和$
(开始和结束)指示模式应该匹配整个字符串此外,如果要防止
""
(空字符串)被匹配,可以将所有*
替换为+
您需要断言单词的开始/结束边界
\b
,然后在三个不同的字符类之间进行转换|
:Demo
您还可以使用更简单、更快的regex
\b[xyz]+\b
,并与Python逻辑结合使用:Python Demo
使用前瞻确保包含三个(或更多)不同字符的任何字符串失败:
见proof
Python:
解释
相关问题 更多 >
编程相关推荐