Python 模式匹配。匹配 'c[任意数量的连续 a、b、c 或 b、c、a 等。 ]t'
对不起,我的标题,我无法想出一个干净的方式来问我的问题。
在Python中,我想匹配一个表达式'c[some stuff]t',其中[some stuff]可以是任意数量的连续a、b或c并且以任意顺序。
例如,这些工作: 'ct'、'猫'、'cbbt'、'caaabbct'、'cbbccaat'
但这些不会: 'cbcbbaat'、'caaccbabbt'
编辑:a、b 和 c 只是一个示例,但我真的希望能够将其扩展到更多字母。我对正则表达式和非正则表达式解决方案感兴趣。
Sorry about the title, I couldn't come up with a clean way to ask my question.
In Python I would like to match an expression 'c[some stuff]t', where [some stuff] could be any number of consecutive a's, b's, or c's and in any order.
For example, these work:
'ct', 'cat', 'cbbt', 'caaabbct', 'cbbccaat'
but these don't:
'cbcbbaat', 'caaccbabbt'
Edit: a's, b's, and c's are just an example but I would really like to be able to extend this to more letters. I'm interested in regex and non-regex solutions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尚未经过彻底测试,但我认为这应该可行:
这与
a
、b
或c
的运行相匹配(即([abc ])\1*
部分),而负前瞻(?!.*\1)
确保运行后不存在该字符的其他实例。(编辑:修复了解释中的拼写错误)
Not thoroughly tested, but I think this should work:
This matches runs of
a
,b
orc
(that's the([abc])\1*
part), while the negative lookahead(?!.*\1)
makes sure no other instance of that character is present after the run.(edit: fixed a typo in the explanation)
不确定您对正则表达式的重视程度,但这里有一个使用不同方法的解决方案:
如果一组中间字符是
set('abc')
的子集,则字符串匹配,并且字符串的数量groupby()
返回的组与集合中的元素数量相同。Not sure how attached you are to regex, but here is a solution using a different method:
The string matches if a set of the middle characters is a subset of
set('abc')
and the number of groups returned bygroupby()
is the same as the number of elements in the set.我相信您需要显式编码
a
s、b
s 和c
s 的所有可能排列:请注意,这是一个效率极低的查询,可能会走回头路很多。
I believe you need to explicitly encode all possible permutations of
a
s,b
s andc
s:Note that this is an extremely inefficient query which may backtrack a lot.
我不知道 Python 正则表达式引擎,但听起来你只是想直接写出 6 种不同的可能顺序。
I don't know the Python regex engine, but it sounds like you just want to write out the 6 different possible orderings directly.
AFAIK 没有“紧凑”的方法来做到这一点......
AFAIK there's no "compact" way of doing this...