【问题标题】:Python Re: Multiple Capturing GroupsPython Re:多个捕获组
【发布时间】:2017-10-08 08:14:04
【问题描述】:

我在构建一个有效且正确的模式以 re.finditer 在一个模式中使用多个捕获组时遇到问题。我有以下字符串要搜索数据。

search_string="""
option.Map['2015'] = new CG.New.Option('text1', '2015', 100, 200);
option.Map['2016'] = new CG.New.Option('text2', '2016', 150, 210);
option.Map['2017'] = new CG.New.Option('text3', '2017', 160, 260);
"""

我想使用 Python 正则表达式来提取文本、年份和数字。我的模式如下所示:

pattern=r"option.Map\[\'(.*)\'] = new CG\.New\.Option\(\'(.*)\',\'(.*)\',(.*),(.*)\);"

我的代码如下所示:

for finding in re.finditer(pattern,search_string):
    print(finding.group(1))
    print(finding.group(2))
    print(finding.group(3))
    print(finding.group(4))
    print(finding.group(5))

我知道我的模式不对,但我不知道为什么。

我期望/想要实现的输出如下所示:

2015
text1
2015
100
200
2016
text2
2016
150
210
2017
text3
2017
160
260

【问题讨论】:

  • unbalanced parenthesis at position 72 有提示吗?
  • @JonClements 感谢您的提示。更新了问题。仍然打印零结果。
  • 你不适合空间... :)

标签: python regex python-3.x regex-group capturing-group


【解决方案1】:

您需要考虑数字后的空格,例如:

import re

search_string = """
option.Map['2015'] = new CG.New.Option('text1', '2015', 100, 200);
option.Map['2016'] = new CG.New.Option('text2', '2016', 150, 210);
option.Map['2017'] = new CG.New.Option('text3', '2017', 160, 260);
"""

pattern = r"option.Map\['(.*?)'\] = new CG.New.Option\('(.*?)', '(.*?)', (\d+), (\d+)\);"

然后:

for match in re.finditer(pattern, search_string):
    print(*match.groups(), sep='\n')

给你:

2015
text1
2015
100
200
2016
text2
2016
150
210
2017
text3
2017
160
260

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多