Regexp python - 查找子字符串

use*_*582 1 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())
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

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

r = re.compile(r'%(.*?)\b')
Run Code Online (Sandbox Code Playgroud)

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

r = re.compile(r'%(\w+)\b')
Run Code Online (Sandbox Code Playgroud)

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

r = re.compile(r'%\w+\b')
Run Code Online (Sandbox Code Playgroud)