开发者

Swapping token values in a string through regex

I have tokenized names (strings), with the tokens separated by underscores, which will always contain a "side" token by the value of M, L, or R.

The presence of that value is guaranteed to be unique (no repetitions or dangers that other tokens might get similar values). In example:

foo_M_bar_type
foo_R_bar_type
foo_L_bar_type

I'd like, in a single regex, to swap L for R and viceversa whenever found, and M to be left untouched. IE the above would become:

foo_M_bar_type
foo_L_bar_type
foo_R_bar_type

when pushed through this ideal expression.

This was what I thought to be a 10 minutes exercise while writing some simple stuff, that I couldn't quite crack as concisely as I wanted to.

The problem itself was of course trivial to solve with one condition that changes the pa开发者_开发技巧ttern, but I'd love some help doing it within a single re.sub() Of course any food for thought is always welcome, but this being an intellectual exercise that me and a couple colleagues failed at I'd love to see it cracked that way.

And yes, I'm fully aware it might not be considered very Pythonic, nor ideal, to solve the problem with a regex, but humour me please :)

Thanks in advance


This answer [ab]uses the replacement function:

>>> s = "foo_M_bar_type foo_R_bar_type foo_L_bar_type"
>>> import re
>>> re.sub("_[LR]_", lambda m: {'_L_':'_R_','_R_':'_L_'}[m.group()], s)
'foo_M_bar_type foo_L_bar_type foo_R_bar_type'
>>>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜