0

I'm trying to get this regex to pick out both 7gh and 7ui but I can only get it to pick out the first one. If anyone knows how to amend the regex such that it also picks out 7ui, I would seriously appreciate it. I should also point out that I mean strings separated by a space.

b = re.search(r'^7\w+','7gh ghj 7ui')
c = b.group()
3
  • Possible duplicate of Python regex findall Commented Jul 31, 2017 at 8:42
  • ^essentially, use findall instead of search Commented Jul 31, 2017 at 8:43
  • 1
    What about a7b? Both solutions would currently pick it as 7b - is that correct? Commented Jul 31, 2017 at 8:46

3 Answers 3

2

Remove ^ and use findall() :

>>> re.findall(r'7\w+','7gh ghj 7ui')
['7gh', '7ui']
Sign up to request clarification or add additional context in comments.

1 Comment

that doesn't work. That only captures the first string with 7
1

You need to remove ^ (start of string anchor) and use re.findall to find all non-overlapping matches of pattern in string:

import re
res = re.findall(r'7\w+','7gh ghj 7ui')
print(res)

See the Python demo

If you need to get these substrings as whole words, enclose the pattern with a word boundary, \b:

res = re.findall(r'\b7\w+\b','7gh ghj 7ui')

5 Comments

difference of few sec :)
They probably want a word boundary in there to avoid picking up bob7something...
@akashkarothiya Yeah, but I think OP might need further tweaking, so, I also suggest a word boundary.
@WiktorStribiżew much appreciated :) helpful
@bobsmith76 you should also consider Wikter's 2nd method for future reference, using \b, Please see
0

You may find it easier to just not use regex

[s for s in my_string.split() if s.startswith('7')]

1 Comment

No, I'm trying to understand how regexes work. I'm not trying to get something done.

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.