Python Regex not returning
I have a function that needs to return a specific number from a mysql table. The number of filtered string using regular expressions ^\((\d*),\)$
. The original string (36,)
and regular expression 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 then I call the function:
return db().fo('SELECT id FROM `GIP-Schema`.user WHERE name = \'{0}\''.format(name))
source to share
You need to get the content of group 1 because ^\((\d*),\)$
pattern matches (
at the beginning of the line than maps to zero or more digits of group 1 (I suggest writing one or more digits) and then matches ,)
at the end of the line. Also, it's a good idea to first check if a match is 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 regex demo
source to share