繁体   English   中英

Python正则表达式子组捕获

[英]Python Regex Subgroup Capturing

我正在尝试解析以下字符串:

constructor: function(some, parameters, here) {

使用以下正则表达式:

re.search("(\w*):\s*function\((?:(\w*)(?:,\s)*)*\)", line).groups()

我得到了:

('constructor', '')

但我期待的更像是:

('constructor', 'some', 'parameters', 'here')

我错过了什么?

如果您将模式更改为:

print re.search(r"(\w*):\s*function\((?:(\w+)(?:,\s)?)*\)", line).groups()

你会得到:

('constructor', 'here')

这是因为(来自docs ):

如果一个组包含在多次匹配的模式的一部分中,则返回最后一个匹配。

如果你可以一步到位,我不知道如何做到这一点。 您的替代方案当然是做以下事情:

def parse_line(line):
    cons, args = re.search(r'(\w*):\s*function\((.*)\)', line).groups()
    mats = re.findall(r'(\w+)(?:,\s*)?', args)
    return [cons] + mats

print parse_line(line)  # ['constructor', 'some', 'parameters', 'here']

一种选择是使用更先进的正则表达式 ,而不是股票re 除了其他好处之外,它还支持captures ,与groups不同, captures保存每个匹配的子字符串:

>>> line = "constructor: function(some, parameters, here) {"
>>> import regex
>>> regex.search("(\w*):\s*function\((?:(\w+)(?:,\s)*)*\)", line).captures(2)
['some', 'parameters', 'here']

re模块不支持重复捕获:组计数是固定的。 可能的解决方法包括:

1)将参数捕获为字符串,然后将其拆分:

match = re.search("(\w*):\s*function\(([\w\s,]*)\)", line).groups()
args = [arg.strip() for arg in math[1].split(",")]

2)将参数捕获为字符串,然后找到它:

match = re.search("(\w*):\s*function\(([\w\s,]*)\)", line).groups()
args = re.findall("(\w+)(?:,\s)*", match[1])

3)如果您的输入字符串已经过验证,您可以找到所有内容:

re.findall("(\w+)[:,)]", string)

或者,您可以使用正则表达式模块和captures(),如@georg所建议的那样。

您可能需要在这里两个操作( searchfindall ):

[re.search(r'[^:]+', given_string).group()] + re.findall(r'(?<=[ (])\w+?(?=[,)])', given_string)

Output: ['constructor', 'some', 'parameters', 'here']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM