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()
bobsmith76
  • 160
  • 1
  • 9
  • 26

3 Answers3

2

Remove ^ and use findall() :

>>> re.findall(r'7\w+','7gh ghj 7ui')
['7gh', '7ui']
akash karothiya
  • 5,736
  • 1
  • 19
  • 29
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')
Graham
  • 7,431
  • 18
  • 59
  • 84
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

You may find it easier to just not use regex

[s for s in my_string.split() if s.startswith('7')]
Sayse
  • 42,633
  • 14
  • 77
  • 146