简体   繁体   English

python中带有re.search的正则表达式不起作用

[英]Regular expression with re.search in python doesn't work

I wanted to write a regular expression for a string test = "ID=ss59537-RA:exon:0;Parent=ss59537-RA;" 我想为字符串test = "ID=ss59537-RA:exon:0;Parent=ss59537-RA;"写一个正则表达式test = "ID=ss59537-RA:exon:0;Parent=ss59537-RA;" and I so I had this searchstr = re.compile(r'(ID = ss[\\d]+-RA)(:)(exon:[\\d]+)(;)(Parent = ss[\\d]+-RA;)') but when I tried to run the re.search command, I am not getting anything back. 所以我有了这个searchstr = re.compile(r'(ID = ss[\\d]+-RA)(:)(exon:[\\d]+)(;)(Parent = ss[\\d]+-RA;)')但是当我尝试运行re.search命令时,我什么也没回来。 What am I doing wrong here? 我在这里做错了什么?

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)

I made sure the regular expression matches the string but when I ran it with reg.search , it doesn't work. 我确保正则表达式与字符串匹配,但是当我使用reg.search运行它时,它不起作用。

It seems you planned to allow any number of spaces around the = signs. 您似乎计划在=号前后留出任意数量的空格。 You may use \\s* instead of literal spaces to match any 0 whitespace chars. 您可以使用\\s*而不是文字空间来匹配任何0个空白字符。 I also advise removing [ and ] from around single atoms ( [\\d] = \\d ), and move the last ) before the ; 我还建议从单个原子( [\\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')

See the Python demo . 参见Python演示

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

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