0

I'm trying to write an python script to collect one specific function's parameters. Parameters can be in multiple lines like this:

str = "getParameters(['ABCD_1','ABCD_2',\
                       'ABCD_3','ABCD_4'])\

This works already: (it can catch every words between ' and '):

parameters = re.findall(r'\'[\w-]+\'', str)
for parameter in parameters:
   print parameter

But I want that only in case of getParameters function the parameters to be collect, and this does not work:

getparameters = re.findall(r'getParameters\(\[[\w-]+', str, re.X|re.DOTALL)
for line in getparameters:
    print line

Please suggest!

5
  • Just to be completely clear: this is the function parameters of code written in Python using Python? Commented Jan 15, 2013 at 10:18
  • 2
    To parse python code in python check out the ast module Commented Jan 15, 2013 at 10:21
  • Yes, actually I want to process python code with python regexp. Commented Jan 15, 2013 at 10:31
  • What should be your output? Commented Jan 15, 2013 at 11:09
  • the parameters of the getParameters function Commented Jan 15, 2013 at 11:54

2 Answers 2

2

Here is an example using ast, just for fun.

import ast

module = ast.parse(
    """getParameters(['ABCD_1','ABCD_2',
                      'ABCD_3','ABCD_4'])""")

for item in module.body:
    if isinstance(item.value, ast.Call) and item.value.func.id == 'getParameters':
        parameters = [each.s for each in item.value.args[0].elts]

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

3 Comments

Hi, thanks I would like to try but: NameError: name 'ast' is not defined
Hi,Could you please help me in using this AST?
@Balee13: You forgot the first line.
0

If you're fixed on using RegEx and if your function occurs exactly once, you can try:

re.findall('\'(\w+)\',?', re.search('(getParameters\(.+?\))', x, re.X|re.S).group(1), re.X|re.S)

It's not ideal, but it works. I am sure there is a better way to do this.

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.