0

I am trying to parse a file and split the line in python. Currently i can parse the file and load it into a list.

I am trying to take each line and split it by the parenthesis,

'datediff(varchar(30),timestamp(3),timestamp(3))'
reverse(text)
checkcluster(int,int,int,int,int)
declaredown(int)

I am trying to extract the parameters in side the function as so:

['varchar(30),timestamp(3),timestamp(3)','text','int,int,int,int,int','int']

However the result i am getting is:

['varchar(30', 'text', 'int,int,int,int,int', 'int']

I believe its because of bracket in varchar. Is there a way to split it just by the first occurrence and last occurrence of parenthesis?

1

1 Answer 1

3

Is there a way to split it just by the first occurrence and last occurrence of parenthesis?

Yes, use partition and rpartition.

>>> s = 'datediff(varchar(30),timestamp(3),timestamp(3))'
>>> s.partition("(")
('datediff', '(', 'varchar(30),timestamp(3),timestamp(3))')
>>> s.partition("(")[2]
'varchar(30),timestamp(3),timestamp(3))'
>>> s.partition("(")[2].rpartition(")")
('varchar(30),timestamp(3),timestamp(3)', ')', '')
>>> s.partition("(")[2].rpartition(")")[0]
'varchar(30),timestamp(3),timestamp(3)'

 

>>> def extract(s):
...     return s.partition("(")[2].rpartition(")")[0]
...
>>> print(extract('datediff(varchar(30),timestamp(3),timestamp(3))'))
varchar(30),timestamp(3),timestamp(3)
>>> print(extract('reverse(text)'))
text
>>> print(extract('checkcluster(int,int,int,int,int)'))
int,int,int,int,int
>>> print(extract('declaredown(int)'))
int
Sign up to request clarification or add additional context in comments.

2 Comments

what if i were to use a function with no parameter as so: getnextcallid(). Is it possible to extract an display an empty string. eg. ' '' '?
how would i partition just the name of the function? eg. s = 'datediff(varchar(30),timestamp(3),timestamp(3))' to just s='datediff'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.