简体   繁体   English

正则表达式替换 %variables%

[英]Regex to replace %variables%

I've been yanking clumps of hair out for 30 minutes doing this one...我一直在拉头发30分钟做这个......

I have a dictionary, like so:我有一本字典,像这样:

{'search': 'replace',
 'foo':    'bar'}

And a string like this:还有这样的字符串:

Foo bar %foo% % search %.

I'd like to replace each variable with it's equivalent text from the dictionary:我想用字典中的等效文本替换每个变量:

Foo bar bar replace.

My current regex fails, so here it is ( key and value are from dictionary.items() ):我当前的正则表达式失败,所以它是( keyvalue来自dictionary.items() ):

 re.sub(r'%\d+' + key + '[^%]\d+%', value, text)

Any help would be appreciated, as this regex stuff is driving me nuts...任何帮助将不胜感激,因为这个正则表达式的东西让我发疯......

If you're flexible with your syntax in your string, Python has a built in mechanism for that:如果您对字符串中的语法很灵活,Python 有一个内置机制:

>>> print 'Hello, %(your_name)s, my name is %(my_name)s' % {'your_name': 'Blender', 'my_name': 'Ken'}
Hello, Blender, my name is Ken

Alternatively, if you want that syntax, I'd avoid regular expressions and just do this:或者,如果你想要那种语法,我会避免使用正则表达式,而是这样做:

>>> vars = {'search': 'replace',
...  'foo':    'bar'}
>>> mystring = "Foo bar %foo% % search %."
>>> for k, v in vars.items():
...     mystring = mystring.replace('%%%s%%' % k, v)
... 
>>> print mystring
Foo bar bar % search %.

If you want it in one statement, you could do the following (assuming s is the string and d is the dictionary):如果您想在一个语句中使用它,您可以执行以下操作(假设 s 是字符串,d 是字典):

re.sub(r"[%]\s*[^%]+\s*[%]",lambda k:d.get(k[1,-1].strip(),k),s)

This uses a function in the replacement part to get each value from the dictionary, and ignores if it is not in the dictionary.这在替换部分使用 function 从字典中获取每个值,如果不在字典中则忽略。

Edit: fixed bug with unwanted whitespace appearing in lookup key编辑:修复了查找键中出现不需要的空格的错误

Maybe I'm missing something, but wouldn't the following regex just work?也许我遗漏了一些东西,但下面的正则表达式不会起作用吗?

re.sub(r'%\s?' + key + '\s?%', value, text)

The only thing that's a bit special are the optional spaces;唯一有点特别的是可选空格; they can be matched with \s?它们可以与\s? . .

Using the replacement function support of re.sub :使用re.sub的替换 function 支持:

def replace(s, kw, pattern=re.compile(r'%\s*(\w+)\s*%')):
    """
    Replace delimited keys in a string with values from kw.

    Any pattern may be used, as long as the first group defines the lookup key.
    """
    lookup = lambda match: kw.get(match.group(1), match.group())
    return pattern.sub(lookup, s)

>>> replace('Foo bar %foo% % search %.', {'search': 'replace', 'foo': 'bar'})
'Foo bar bar replace.'

You can change the lookup function to customize how lookup errors are treated, and so on.您可以更改lookup function 以自定义如何处理查找错误,等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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