确保正则表达式不匹配空字符串 - 但有一些警告 [英] Make sure regex does not match empty string - but with a few caveats
问题描述
有一个问题我需要做,但有一些注意事项使它变得困难.
There is a problem that I need to do, but there are some caveats that make it hard.
问题:匹配字母表 {abc} 上最多包含一个 a
的所有非空字符串.
Problem: Match on all non-empty strings over the alphabet {abc} that contain at most one a
.
示例
一个
ABC
英国广播公司
bbcabb
a
abc
bbca
bbcabb
非示例
aa
呜呜
aa
bbaa
警告:您不能使用前瞻/后视.
Caveats: You cannot use a lookahead/lookbehind.
我拥有的是这个:
^[bc]*a?[bc]*$
但它匹配空字符串.也许是一个提示?我知道任何事情都会有帮助
but it matches empty strings. Maybe a hint? Idk anything would help
(如果重要的话,我正在使用 python).
(And if it matters, I'm using python).
推荐答案
据我了解您的问题,唯一的问题是您当前的模式匹配空字符串.为了防止这种情况,您可以使用 字边界 \b
至少需要一个单词字符.
As I understand your question, the only problem is, that your current pattern matches empty strings. To prevent this you can use a word boundary \b
to require at least one word character.
^\b[bc]*a?[bc]*$
另一种选择是 alternate 在 组.匹配由任意数量的 [bc]
或一个或多个 [bc]
从头到尾包围的 a
,它可能如下所示:^(?:[bc]*a[bc]*|[bc]+)$
Another option would be to alternate in a group. Match an a
surrounded by any amount of [bc]
or one or more [bc]
from start to end which could look like: ^(?:[bc]*a[bc]*|[bc]+)$
这篇关于确保正则表达式不匹配空字符串 - 但有一些警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!