[英]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. 我正试图让此正则表达式同时选择7gh和7ui,但我只能让它选择第一个。 If anyone knows how to amend the regex such that it also picks out 7ui, I would seriously appreciate it.
如果有人知道如何修改正则表达式,使其也可以选择7ui,我将非常感谢。 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()
: 删除
^
并使用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 : 您需要删除
^
(字符串锚点的开头),然后使用re.findall
查找string中模式的所有非重叠匹配项 :
import re
res = re.findall(r'7\w+','7gh ghj 7ui')
print(res)
See the Python demo 参见Python演示
If you need to get these substrings as whole words , enclose the pattern with a word boundary, \\b
: 如果您需要将这些子字符串作为整个单词获取 ,请使用单词边界
\\b
将模式括起来:
res = re.findall(r'\b7\w+\b','7gh ghj 7ui')
您可能会发现不使用正则表达式会更容易
[s for s in my_string.split() if s.startswith('7')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.