您可以使用单个正则表达式来解析函数参数吗? [英] Can You Use a Single Regular Expression to Parse Function Parameters?

查看:310
本文介绍了您可以使用单个正则表达式来解析函数参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

有一个程序文件,该文件在某些​​位置包含以下代码段.

There is a program file that contains the following code snippet at some point in the file.

...

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

...

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

This function may contain any number of parameters but they must be strings separated by commas. All the parameter strings are lowercase words.

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

I want to be able to parse out each of the parameters using a regular expression. For example the resulting list in python would be as follows:

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

尝试的解决方案

使用python RE模块,我可以将问题分为两部分来实现.

Using the python RE module, I was able to achieve this by breaking the problem into two parts.

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

  1. Find the function in the code and extract the list of parameters.

plist = re.search(r'food\((.*)\)', programString).group(1)

  • 使用另一个正则表达式拆分列表.

  • Split the list using another regular expression.

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

  • 问题

    无论如何,我可以使用一个正则表达式而不是两个正则表达式来实现这一点吗?

    Is there anyway I could achieve this with one regular expression instead of two?

    修改

    多亏了蒂姆·皮茨克(Tim Pietzcker)的回答,我才找到了一些相关的问题:

    Thanks to Tim Pietzcker's answer I was able to find some related questions:

    1. Python正则表达式-如何捕获通配符表达式中的多个组?
    2. 哪些正则表达式支持捕获(相对于捕获组)?
    1. Python regular expressions - how to capture multiple groups from a wildcard expression?
    2. Which regex flavors support captures (as opposed to capturing groups)?

    推荐答案

    回答您的问题可以在单个正则表达式中完成吗?":是的,但是在Python中不是.

    To answer your question "Can it be done in a single regex?": Yes, but not in Python.

    如果您想仅使用一个正则表达式来匹配并捕获(分别)示例中未知数量的匹配项,则需要

    If you want to match and capture (individually) an unknown number of matches as in your example, using only a single regular expression, then you need a regex engine that supports captures (as opposed to capturing groups). Only .NET and Perl 6 do this currently.

    因此在Python中,您需要分两步进行操作(find整个food(...)函数调用,然后findall单独匹配,并按Dingo的建议使用第二个正则表达式).

    So in Python, you either need to do it in two steps (find the entire food(...) function call, and then findall individual matches with a second regex as suggested by Dingo).

    或者使用像Paul McGuire的pyparsing这样的解析器.

    Or use a parser like Paul McGuire's pyparsing.

    这篇关于您可以使用单个正则表达式来解析函数参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆