简体   繁体   中英

How do you write a regex in python which picks out all strings beginning with a specific number

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()

Remove ^ and use findall() :

>>> re.findall(r'7\w+','7gh ghj 7ui')
['7gh', '7ui']

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')

您可能会发现不使用正则表达式会更容易

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM