user349594
user349594

Reputation:

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 pattern, 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

Upvotes: 0

Views: 188

Answers (1)

John Machin
John Machin

Reputation: 82924

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'
>>>

Upvotes: 3

Related Questions