-1

Given :

s = "SELECT * FROM THIS_TABLE WHERE COL='123'"

Return the table name from the sql query which is always between 'FROM ' and ' WHERE'

Regex expression that I've tried returns nothing :

re.search('FROM\s+(.*)\s+WHERE', s.upper())

Expected output :

'THIS_TABLE'
Henry-G
  • 131
  • 1
  • 8
  • I think, you should use double quotes there. [`re.search()`](https://docs.python.org/3/library/re.html#re.Match.group) returns [match object](https://docs.python.org/3/library/re.html#match-objects) or `None`, so to get captured group you need to call [`Match.group()`](https://docs.python.org/3/library/re.html#re.Match.group). – Olvin Roght Jun 10 '20 at 07:57
  • Corrected the string with double quotes. – Henry-G Jun 10 '20 at 08:00

1 Answers1

0

Indeed, you need to use doublequotes so the singlequotes in your query aren't interpreted. Additionnaly, you can add 'r' in front of the string to have python interpret it as litteral.

Your result is a re.Match object, of which it's elements contain what you're searching for.

Here's a working copy:

s = r"SELECT * FROM THIS_TABLE WHERE COL='123'"
result = re.search('FROM\s+(.*)\s+WHERE', s.upper())[1]
print(result)

prints 'THIS_TABLE'

Orsiris de Jong
  • 2,819
  • 1
  • 26
  • 48
  • Or throw an error in case if search returned `None`. – Olvin Roght Jun 10 '20 at 08:03
  • Indeed, but as this is a proof of concept, the error handling is out of context. Using a try except (TypeError, IndexError) will solve this. Using Match.group also will require an IndexError error handling. – Orsiris de Jong Jun 10 '20 at 08:08
  • I've tried to say that it'll be good to check result of search before trying to read matches. – Olvin Roght Jun 10 '20 at 08:10