gpt4 book ai didi

python - python 中的连接正则表达式有时会失败

转载 作者:太空宇宙 更新时间:2023-11-03 18:41:25 27 4
gpt4 key购买 nike

我使用正则表达式来验证某些数据的格式是否正确,但有时会失败。

我有多个字段的数据条目。只有少数字段在格式上足够一致,或者从不为空而无法验证,因此我创建了一个小的正则表达式来匹配这些字段。我想将字段和正则表达式连接在一起,并为每个条目调用一次 match() 。尽管所有各个字段都与其各自的正则表达式匹配,但连接检查失败。

regs = ['\d.\d','[a-z][a-z]','\d{1,2}'] # list of regexes
indeces = [4, 15, 77] # list of indeces
for line in stdin:

linesplit = line.rstrip().split('\t')
testline = []
for index in indeces:
testline.append(linesplit[index])

for i, e in enumerate(testline):
print i, e, re.match(regs[i], e)

这工作正常,但当我尝试最后一点时,有时会失败。

fullregex = re.compile('\t'.join(regs))
f = fullregex.match('\t'.join(testline).rstrip())
print 'F', f, '!'

我的 fullregex 是否有问题,或者我得到的匹配只是误报?

最佳答案

您的各个正则表达式可以在列中匹配,但您的连接表达式则不能。

例如输入:

['1.1 bar', 'hello', '123 is a number']

匹配您的个人表达式,但当使用制表符连接时,不再匹配 fullregex模式。

添加[^\t]*作为表达式中的“填充”,以允许选项卡周围有额外的非制表符:

fullregex = re.compile(r'[^\t]*\t[^\t]*'.join(regs))

演示:

>>> import re
>>> regs = ['\d.\d','[a-z][a-z]','\d{1,2}']
>>> testline = ['1.1 bar', 'hello', '123 is a number']
>>> for i, (expr, line) in enumerate(zip(regs, testline)):
... print i, line, re.match(expr, line)
...
0 1.1 bar <_sre.SRE_Match object at 0x101c17e68>
1 hello <_sre.SRE_Match object at 0x101c17e68>
2 123 is a number <_sre.SRE_Match object at 0x101c17e68>
>>> re.match('\t'.join(regs), '\t'.join(testline))
>>> re.match(r'[^\t]*\t[^\t]*'.join(regs), '\t'.join(testline))
<_sre.SRE_Match object at 0x101c17e68>

如果您希望正则表达式验证整个列,则可以:

  1. 使用 zip() 测试每一列和 anchor ( ^$ ):

    all(re.match('^{}$'.format(expr), col) for expr, col in zip(regs, testline))

    哪里all()只返回True如果所有表达式都匹配并且 anchor 确保表达式覆盖整个列,而不仅仅是一个子集。

  2. 或使用 \t 连接列,但也要添加 anchor :

    re.match('^{}$'.format('\t'.join(regs)), '\t'.join(testline))

演示:

>>> regs = ['\d.\d','[a-z][a-z]','\d{1,2}']
>>> testline = ['1.1', 'he', '12']
>>> all(re.match('^{}$'.format(expr), col) for expr, col in zip(regs, testline))
True
>>> re.match('^{}$'.format('\t'.join(regs)), '\t'.join(testline))
<_sre.SRE_Match object at 0x101caa780>
>>> testline = ['1.1 bar', 'hello', '123 is a number']
>>> all(re.match('^{}$'.format(expr), col) for expr, col in zip(regs, testline))
False
>>> re.match('^{}$'.format('\t'.join(regs)), '\t'.join(testline)) is None
True

关于python - python 中的连接正则表达式有时会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20428392/

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