2

Consider sentence : W U T Sample A B C D

I'm trying to use re.groups after re.search to fetch A, B, C, D (letters in caps after 'Sample'). There could be variable number of letters

Few unsuccessful attempts :

A = re.search('Sample\s([A-Z])\s*([A-Z])*', 'W U T Sample A B C D')
A.groups()
('A', 'B')

A = re.search('Sample\s([A-Z])(\s*([A-Z]))*', 'W U T Sample A B C D')
A.groups()
('A', ' D', 'D')

A = re.search('Sample\s([A-Z])(?:\s*([A-Z]))*', 'W U T Sample A B C D')
A.groups()
('A', 'D')

I'm expecting A.groups() to give ('A', 'B', 'C', 'D')

Taking another example, 'XSS 55 D W Sample R G Y BH' should give the output ('R', 'G', 'Y', 'B', 'H')

3
  • You can use this Commented Mar 31, 2019 at 4:01
  • @CodeManiac Useful tool, but the example regex mentioned does not give ('R', 'G', 'Y', 'B', 'H') for 'XSS 55 D W Sample R G Y BH'. B and H are considered one, which is different from what I want Commented Mar 31, 2019 at 5:54
  • You need to split the matched group in next step Commented Mar 31, 2019 at 6:13

1 Answer 1

1

Most regex engines, including Python's, will overwrite a repeating capture group. So, the repeating capture group you see will just be the final one, and your current approach will not work. As a workaround, we can try first isolating the substring you want, and then applying re.findall:

input = "W U T Sample A B C D"
text = re.search(r'Sample\s([A-Z](?:\s*[A-Z])*)', input).group(1)  # A B C D
result = re.findall(r'[A-Z]', text)
print(result)

['A', 'B', 'C', 'D']
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I suppose two steps would be involved for this.

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.