Coderaemon
Coderaemon

Reputation: 3867

Regex pattern to extract substring

mystring = "q1)whatq2)whenq3)where"

want something like ["q1)what", "q2)when", "q3)where"]

My approach is to find the q\d+\) pattern then move till I find this pattern again and stop. But I'm not able to stop.

I did req_list = re.compile("q\d+\)[*]\q\d+\)").split(mystring)

But this gives the whole string. How can I do it?

Upvotes: 0

Views: 71

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174696

You could try the below code which uses re.findall function,

>>> import re
>>> s = "q1)whatq2)whenq3)where"
>>> m = re.findall(r'q\d+\)(?:(?!q\d+).)*', s)
>>> m
['q1)what', 'q2)when', 'q3)where']

Explanation:

  • q\d+\) Matches the string in the format q followed by one or more digits and again followed by ) symbol.
  • (?:(?!q\d+).)* Negative look-ahead which matches any char not of q\d+ zero or more times.

Upvotes: 2

Related Questions