1

I have a problem building a working and correct pattern to re.finditer with multiple capturing groups in a pattern. I have the following string I want to search for data.

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);
"""

I would like to use Python regex to extract the text, the year, and the numbers. My pattern looks like the following:

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

My code looks like the following:

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

I know that my pattern is off, but I don't know why.

The output I would expect/want to achieve looks like the following:

2015
text1
2015
100
200
2016
text2
2016
150
210
2017
text3
2017
160
260
3
  • Does unbalanced parenthesis at position 72 give a hint? Commented May 9, 2017 at 20:57
  • @JonClements thanks for the hint. Updated the problem. Prints zero findings still though. Commented May 9, 2017 at 21:47
  • You're not catering for spaces... :) Commented May 9, 2017 at 21:51

1 Answer 1

2

You need to take into account the spaces after the numbers, eg:

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+)\);"

Then:

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

Gives you:

2015
text1
2015
100
200
2016
text2
2016
150
210
2017
text3
2017
160
260
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.