Reputation: 409
I have a function that should return a certain number from a mysql table. The number is filtered out of the string using regex like so: ^\((\d*),\)$
. The original string is (36,)
and the regex should change it to this: 36
. But i still get (36,)!
class db:
con = mysql.connect()
cur = con.cursor()
def fo(self, query):
self.cur.execute(query)
return re.search('^\((\d*),\)$',
str(self.cur.fetchone())).group(0)
and further on I call the function:
return db().fo('SELECT id FROM `GIP-Schema`.user WHERE name = \'{0}\''.format(name))
Upvotes: 3
Views: 65
Reputation: 626845
You need to get Group 1 contents because ^\((\d*),\)$
pattern matches (
at the start of the string, than captures into Group 1 zero or more digits (I suggest to capture one or more digits), and then matches ,)
at the end of the string. Also, it is a good idea to first check if a match was found:
def fo(self, query):
self.cur.execute(query)
m = re.search('^\((\d+),\)$', str(self.cur.fetchone()))
res = ''
if m:
res = m.group(1)
return res
See the regex demo
Upvotes: 3
Reputation: 409
Thanks to Wiktor for pointing it out, apparently your first group is a 1, not a 0
.group(0)
-> .group(1)
Upvotes: 1