简体   繁体   中英

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;" 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. 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.

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. I also advise removing [ and ] from around single atoms ( [\\d] = \\d ), and move the last ) before the ; :

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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