正则表达式python - 查找子字符串

时间:2013-05-08 19:23:40

标签: python regex

如何在字符串中找到子字符串的所有实例?

例如,我有字符串("%1 is going to the %2 with %3")。我需要提取此字符串中的所有占位符(%1%2%3

当前代码只能找到前两个,因为结尾不是空格。

import re
string = "%1 is going to the %2 with %3"


r = re.compile('%(.*?) ')
m = r.finditer(string)
for y in m:
 print (y.group())

1 个答案:

答案 0 :(得分:5)

在空格上不匹配,请使用\b匹配字边界:

r = re.compile(r'%(.*?)\b')

您可能希望仅将字符限制为字词而不是.通配符,并匹配至少一个字符:

r = re.compile(r'%(\w+)\b')

您似乎也没有使用捕获组,所以您可以省略:

r = re.compile(r'%\w+\b')
相关问题