代码之家  ›  专栏  ›  技术社区  ›  Nixuz

可以使用单个正则表达式来分析函数参数吗?

  •  2
  • Nixuz  · 技术社区  · 15 年前

    问题

    在文件中的某个点上,有一个程序文件包含以下代码段。

    ...
    
    food($apples$ , $oranges$ , $pears$ , $tomato$){
      ...
    }
    
    ...
    

    此函数可以包含任意数量的参数,但它们必须是用逗号分隔的字符串。所有参数字符串都是小写字母。

    我希望能够使用正则表达式解析出每个参数。例如,python中的结果列表如下:

    ["apples", "oranges", "pears", "tomato"]
    

    尝试的解决方案

    使用python re模块,我可以通过将问题分成两部分来实现这一点。

    1. 在代码中查找函数并提取参数列表。

      plist = re.search(r'food\((.*)\)', programString).group(1)
      
    2. 使用另一个正则表达式拆分列表。

      params = re.findall(r'[a-z]+', plist)
      

    问题

    我是否可以用一个正则表达式而不是两个表达式来实现这一点?

    编辑

    由于Tim Pietzcker的回答,我找到了一些相关问题:

    1. Python regular expressions - how to capture multiple groups from a wildcard expression?
    2. Which regex flavors support captures (as opposed to capturing groups)?
    5 回复  |  直到 15 年前
        1
  •  2
  •   Community Mohan Dere    9 年前
        2
  •  2
  •   PaulMcG    15 年前

    >>> code = """\
    ... ...
    ...
    ... food($apples$ , $oranges$ , $pears$ , $tomato$){
    ...   ...
    ... }
    ... ...
    ... food($peanuts$, $popcorn$ ,$candybars$ ,$icecream$){
    ...   ...
    ... }
    ... """
    >>> from pyparsing import *
    >>> LPAR,RPAR,LBRACE,RBRACE,DOLLAR = map(Suppress,"(){}$")
    >>> param = DOLLAR + Word(alphas) + DOLLAR
    >>> funcCall = "food" + LPAR + delimitedList(param)("parameters") + RPAR + LBRACE
    >>> for fn in funcCall.searchString(code):
    ...   print fn.parameters
    ...
    ['apples', 'oranges', 'pears', 'tomato']
    ['peanuts', 'popcorn', 'candybars', 'icecream']
    

    ... food($peanuts$, $popcorn$ ,/*$candybars$ ,*/$icecream$){
    

    >>> funcCall.ignore(cStyleComment)
    

    >>> for fn in funcCall.searchString(code):
    ...   print fn.parameters
    ...
    ['apples', 'oranges', 'pears', 'tomato']
    ['peanuts', 'popcorn', 'icecream']
    
        3
  •  1
  •   ghostdog74    15 年前

    for line in open("file"):
        line=line.rstrip()
        if line.lstrip().startswith("food") :
            for item in line.split(")"):
                if "food" in item:
                    print item.split("(")[-1].split(",")
    

    $ ./python.py
    ['$apples$ ', ' $oranges$ ', ' $pears$ ', ' $tomato$']
    
        4
  •  0
  •   Dingo    15 年前
    params = re.findall(r'\$([a-z]+)\$', programString)
    
        5
  •  0
  •   CaffGeek    15 年前

    food\((\$(?<parm>\w+)\$\s*,?\s*)+\).*