upendra
upendra

Reputation: 2189

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.

Upvotes: 1

Views: 1366

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

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.

Upvotes: 2

Related Questions