【发布时间】:2019-09-05 13:39:39
【问题描述】:
我需要在 Python 中生成以下正则表达式:
字母表 {a,b} 中所有字符串的集合,其中每个 a 的前面和后面都有 2 个 b。下面我生成了长度为 0 到 4 的有效字符串
有效字符串:[空字符串]、b、bb、bbb、bbbb、bbab等
无效字符串:a、ba、ab、bba、bbab
我的 reg 表达式目前是:“(b|bbabb)+”,它匹配除空字符串之外的所有内容,但由于我想支持空字符串,我将“+”替换为“*”,现在一些原因是为这个字母表中从 1 到 4 的每个字符串(到目前为止我只测试了长度为 4 的字符串)生成一个匹配项。它为以下内容提供匹配项:
{a, b, aa, bb, ab, ba, aaa, bbb, etc..} 即使对于任何具有 a 的字符串都应该失败,其中每个 a 前面没有 2 个 b 并且后面没有2个b的
def alphaf():
return "(b|bbabb)*"
regex = alphaf()
p = re.compile(regex)
#Below are the test strings
test = 'a'
match = p.match(test)
if match is None:
print('No Match: {0}'.format(test))
else:
print('Match: {0}'.format(test))
test = 'b'
match = p.match(test)
if match is None:
print('No Match: {0}'.format(test))
else:
print('Match: {0}'.format(test))
test = 'bbabb'
match = p.match(test)
if match is None:
print('No Match: {0}'.format(test))
else:
print('Match: {0}'.format(test))
test = 'abb'
match = p.match(test)
if match is None:
print('No Match: {0}'.format(test))
else:
print('Match: {0}'.format(test))
test = 'bba'
match = p.match(test)
if match is None:
print('No Match: {0}'.format(test))
else:
print('Match: {0}'.format(test))
test = 'bbbab'
match = p.match(test)
if match is None:
print('No Match: {0}'.format(test))
else:
print('Match: {0}'.format(test))
test = 'bbbabb'
match = p.match(test)
if match is None:
print('No Match: {0}'.format(test))
else:
print('Match: {0}'.format(test))
test = ''
match = p.match(test)
if match is None:
print('No Match: {0}'.format(test))
else:
print('Match: {0}'.format(test))
【问题讨论】:
-
你所拥有的只是一个“原始字符串”,而不是任何可以进行正则表达式搜索的东西。当然,这不可能是您的全部代码,因为
return必须在函数中。另外,我不确定您是否向我们提供了完整的问题描述。是不是像这样:“给定一个列表 if 字符串(或多行字符串),返回那些包含a的字符串(或行),后面跟着两个b's?或类似的东西?跨度> -
是的,就是这样,我只需要生成生成它的正则表达式,感谢您注意到我会更改它。是的,基本上如果有一个“a”,它需要被前后两个“b”包围
-
更新您的问题并展示更多工作(这就是您被否决的原因)。
-
好的,我尽快回来。我更新了问题。所以我删除了'r',它除了空字符串外一切正常,但是当我用kleenee星替换“+”时,现在它匹配每个字符串甚至'a',即使'a'不在组中: (b|bbabb)
-
使用原始字符串没有任何问题。运行 Python,当你得到
>>>提示符时,输入'\n'和r'\n'看看区别。