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))

      

+3


source to share


2 answers


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

+3


source


Wiktor Due to indicate this is obviously your first group - 1, not 0 .group(0)

โ†’.group(1)



+1


source







All Articles