Python 正则表达式子组捕获

标签 python regex

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

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 ):

If a group is contained in a part of the pattern that matched multiple times, the last match is returned.

如果您可以一步完成此操作,我不知道如何做。当然,您的选择是执行以下操作:

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']

关于Python 正则表达式子组捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29020148/

相关文章:

python - 如何使用 Python NLTK 仅打印出 Wo​​rdNet 同义词集中的单词本身?

javascript - 如何在javascript中强制字符串中出现空格

grep - 如何使用grep查找n个字符长的字词?

ios - 用于将 URL 与视频 ID 匹配的正则表达式

regex - Vim 中的正则表达式匹配组捕获

python - Azure SQL 数据库的 Sqlalchemy 问题

python - 为什么 numpy.broadcast "transpose"vstack 和类似函数的结果?

python - 在 MAMP 或 Linux/cPanel 上运行 Python

regex - PowerShell 在匹配后检索 3 个字符

python - Qt - 子部件后面的背景图像