在python中使用re.search进行正则表达式并不起作用

时间:2018-05-14 20:47:19

标签: python regex

我想为字符串test = "ID=ss59537-RA:exon:0;Parent=ss59537-RA;"编写一个正则表达式,所以我有了searchstr = re.compile(r'(ID = ss[\d]+-RA)(:)(exon:[\d]+)(;)(Parent = ss[\d]+-RA;)'),但是当我尝试运行re.search命令时,我没有收到任何回复。我在这做错了什么?

searchstr = re.compile(r'(ID = ss[\d]+-RA)(:)(exon:[\d]+)(;)(Parent = ss[\d]+-RA;)')
test = "ID=ss59537-RA:exon:0;Parent=ss59537-RA;"
match = re.search(searchstr, test)
print(match)

我确保正则表达式与字符串匹配,但是当我使用reg.search运行它时,它不起作用。

1 个答案:

答案 0 :(得分:2)

您似乎计划在=标志周围留出任意数量的空格。您可以使用\s*而不是文字空格来匹配任何0个空格字符。我还建议从单个原子([ = ])周围移除[\d]\d,并移动)之前的最后;

import re
searchstr = re.compile(r'(ID\s*=\s*ss\d+-RA):(exon:\d+);(Parent\s*=\s*ss\d+-RA);')
test = "ID=ss59537-RA:exon:0;Parent=ss59537-RA;"
match = re.search(searchstr, test)
print(match.groups())
# => ('ID=ss59537-RA', 'exon:0', 'Parent=ss59537-RA')

请参阅Python demo

相关问题