gpt4 book ai didi

python - 正则表达式匹配?

转载 作者:太空宇宙 更新时间:2023-11-03 11:34:45 26 4
gpt4 key购买 nike

我在 Python 中有以下正则表达式,

^1?$|^(11+?)\1+$

因为有一个管道'|',我将把它分成2个正则表达式,

^1?$

为此,它应该验证 1 或 值。我说得对吗?

^(11+?)\1+$

对于上面的正则表达式,它将验证值 1111。第一对 11 基于 (11+?),第二对 11 基于\1。

当我尝试在 Python 中执行它时,它只对 1111 返回 true 而不是 11 或空值。我哪里错了吗?

最佳答案

Ted wrote:

For this, it should validate 1 or empty value. Am I correct?

是的,这是正确的。

Ted wrote:

When I attempt to execute it in Python, it returns true only for 1111 but not 11 or empty value. Am I wrong somewhere?

空字符串确实匹配。以下片段:

#!/usr/bin/env python
import re

for n in xrange(0, 51):
ones = '1' * n
matches = re.match(r'^1?$|^(11+?)\1+$', ones)
if matches:
div1 = n if matches.group(1) is None else len(matches.group(1))
div2 = 0 if div1 is 0 else len(ones)/div1
print "[{0:2}]:{1:2} * {2:2} = '{3}'".format(n, div1, div2, ones)

将打印:

[ 0]: 0 *  0 = ''
[ 1]: 1 * 1 = '1'
[ 4]: 2 * 2 = '1111'
[ 6]: 2 * 3 = '111111'
[ 8]: 2 * 4 = '11111111'
[ 9]: 3 * 3 = '111111111'
[10]: 2 * 5 = '1111111111'
[12]: 2 * 6 = '111111111111'
[14]: 2 * 7 = '11111111111111'
[15]: 3 * 5 = '111111111111111'
[16]: 2 * 8 = '1111111111111111'
[18]: 2 * 9 = '111111111111111111'
[20]: 2 * 10 = '11111111111111111111'
[21]: 3 * 7 = '111111111111111111111'
[22]: 2 * 11 = '1111111111111111111111'
[24]: 2 * 12 = '111111111111111111111111'
[25]: 5 * 5 = '1111111111111111111111111'
[26]: 2 * 13 = '11111111111111111111111111'
[27]: 3 * 9 = '111111111111111111111111111'
[28]: 2 * 14 = '1111111111111111111111111111'
[30]: 2 * 15 = '111111111111111111111111111111'
[32]: 2 * 16 = '11111111111111111111111111111111'
[33]: 3 * 11 = '111111111111111111111111111111111'
[34]: 2 * 17 = '1111111111111111111111111111111111'
[35]: 5 * 7 = '11111111111111111111111111111111111'
[36]: 2 * 18 = '111111111111111111111111111111111111'
[38]: 2 * 19 = '11111111111111111111111111111111111111'
[39]: 3 * 13 = '111111111111111111111111111111111111111'
[40]: 2 * 20 = '1111111111111111111111111111111111111111'
[42]: 2 * 21 = '111111111111111111111111111111111111111111'
[44]: 2 * 22 = '11111111111111111111111111111111111111111111'
[45]: 3 * 15 = '111111111111111111111111111111111111111111111'
[46]: 2 * 23 = '1111111111111111111111111111111111111111111111'
[48]: 2 * 24 = '111111111111111111111111111111111111111111111111'
[49]: 7 * 7 = '1111111111111111111111111111111111111111111111111'
[50]: 2 * 25 = '11111111111111111111111111111111111111111111111111'

并且输入 11 不匹配,因为 11 在第 1 组 ((11+?)) 中匹配,这应该是repeated at least once (\1+),事实并非如此(没有重复)。

关于python - 正则表达式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7561232/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com