查找字符串中所有占位符的 pythonic 方法

pythonic way for finding all the placeholders in a string

我有一个字符串,其中包含占位符,由“%”包围。我想获得这些占位符的列表。我试过这个正则表达式

m = re.search('%s(.*)%s' % ('\%', '\%'), message)

在以下字符串上

black %brown% fox jumped over the %lazy% dog

我希望得到

['brown', 'lazy']

但相反,我得到

'brown% fox jumped over the %lazy'

默认情况下,搜索以贪婪模式进行:它将尝试找到最长的匹配文本。

你有两个解决方案:

  • 执行非贪婪搜索(JvdV和xdhmoore在评论区指出),在*旁边添加一个?(.*?)

  • 编辑正则表达式以禁止占位符内的任何 %,使用 [^%] 而不是 .:

    m = re.search('%([^%]*)%', message)
    

注意:我删除了百分比字符串格式。我相信你想要参数化占位符边界,但现在我可能同意 chepner 的意见,我删除了它并在原地写了普通正则表达式。

这是一个正则表达式,用于查找 % 歌曲之间的项目。

'%(\w+)%'

之后你应该使用

string ='black %brown% fox jumped over the %lazy% dog'
m = re.findall(r'%(\w+)%', string)
print(m)

你可以在修饰符后面加上?得到一个非贪婪搜索-

re.findall('%s(.*?)%s' % ('\%', '\%'), message)
import re
text =" black %brown% fox jumped over the %lazy% dog"
print(re.findall(r'%(.*?)%', text))
import re
message ='black %brown% fox jumped over the %lazy% dog'
m = re.findall(r'%(.*?)%', message)
print(m)

输出:-

['brown', 'lazy']

[已解决]: 使用正则表达式

import re

# Store your string
my_str = 'black %brown% fox jumped over the %lazy% dog'

# Find matches
match = re.findall('%([^%]*)%', my_str)

# Print everything
print match

# Iterate
for item in match:
    print item

[结果]:

['brown', 'lazy']