繁体   English   中英

带有数字和大写字母的字符串的正则表达式匹配失败

[英]Regex match of a string with numbers and uppercase letters failing

我正在尝试在下面的列表中匹配lasko17A565 ,但是正则表达式失败?具体来说,我正在尝试查找前面的变量train中存在的字符串,后面是数字和大写字母的任意组合,有人可以提供指导以防止失败吗?

import re
xbsfindupdates_output_list  = ['project-707.1.5 was found in the following updates of lasko:', '\tlasko17A565', '\tNewestlasko', '\tBuiltlasko']
train = 'lasko'
found_new_SDK = False
for SDK in xbsfindupdates_output_list:
    if re.match(r'%s[0-9A-Z]'%train,SDK):
        found_new_SDK = True
print found_new_SDK

当前输出:

False

预期的输出:

True

我怀疑错误在于您如何构建此处要使用的正则表达式模式。 我建议将输入列表按空格连接在一起以形成单个输入字符串,然后将以下正则表达式与re.findall一起re.findall

\b(lasko[A-Z0-9]+)\b

边界这个词在这里是合适的,因为train值应该在左边用制表符限制,在右边用空格限制。

xbsfindupdates_output_list  = ['project-707.1.5 was found in the following updates of lasko:', '\tlasko17A565', '\tNewestlasko', '\tBuiltlasko']
train = 'lasko'
inp = ' '.join(xbsfindupdates_output_list)
pattern = r'\b(' + train + r'[A-Z0-9]+)\b'
matches = re.findall(pattern, inp)
print(matches)

打印:

['lasko17A565']

编辑:

如果您只想查找是否存在匹配项,请尝试:

xbsfindupdates_output_list  = ['project-707.1.5 was found in the following updates of lasko:', '\tlasko17A565', '\tNewestlasko', '\tBuiltlasko']
train = 'lasko'
inp = ' '.join(xbsfindupdates_output_list)
pattern = r'\b' + train + r'[A-Z0-9]+\b'
if re.search(pattern, inp):
    print("MATCH")
else:
    print("NO MATCH")

尝试这个:

for SDK in xbsfindupdates_output_list:
print(SDK,re.search("%s[0-9A-Z]+"%train,SDK))
if re.match("%s[0-9A-Z]+"%train,SDK.strip()):
    print("FOUND")
    found_new_SDK = True
print (found_new_SDK)

如果两个字符串相同,则re.match返回True。 尝试re.search,它将在字符串中搜索所需的模式

匹配对象始终为true,如果没有匹配项,则不返回None。 只是测试真实性。 因此,我没有在这里使用re.search进行匹配:

xbsfindupdates_output_list  = ['project-707.1.5 was found in the following updates of lasko:', '\tlasko17A565', '\tNewestlasko', '\tBuiltlasko']
    train = 'lasko'
    found_new_SDK = False
    for SDK in xbsfindupdates_output_list:
          if re.search(r'\b' + train + r'[\d\S]+', SDK):
               found_new_SDK = True
    print found_new_SDK

O / p:是

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM