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
  • 489
  • 7
  • 22

3 Answers3

2

Remove ^ and use findall() :

>>> re.findall(r'7\w+','7gh ghj 7ui')
['7gh', '7ui']
akash karothiya
  • 5,500
  • 1
  • 16
  • 26
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,035
  • 17
  • 57
  • 82
Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
0

You may find it easier to just not use regex

[s for s in my_string.split() if s.startswith('7')]
Sayse
  • 41,425
  • 14
  • 72
  • 139