3

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))
6
  • 2
    .group(0) -> .group(1) Commented May 13, 2017 at 19:57
  • Capture group(1) or change regex to ^\(?:(\d*),\)$. Commented May 13, 2017 at 19:58
  • Wow, that easy? Damn... Commented May 13, 2017 at 19:58
  • group(0) is the whole matched expression. Commented May 13, 2017 at 19:59
  • @juanpa.arrivillaga I don't understand what you mean, it's the value that the regex is used on, if that wouldn't work, there would be no point in regex, right? Commented May 13, 2017 at 20:03

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

Thanks to Wiktor for pointing it out, apparently your first group is a 1, not a 0 .group(0) -> .group(1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.