Home > Software engineering >  Using re.sub to substitute a word with another word that is already in the string?
Using re.sub to substitute a word with another word that is already in the string?

Time:10-14

Sorry if the question is confusing, here is the example:

string = "he showed his tooths [: teeth ] to the dentist"

I would like to substitute the word preceding [:] with what is between [:]. I suppose it's possible to do it using re.sub, but I'm not quite sure how to write it.

expected output:

"he showed his teeth to the dentist"

CodePudding user response:

How about:

>>> import re
>>> string = "he showed his tooths [: teeth ] to the dentist"
>>> re.sub(r"(\w ) (?:\[: (. ?) \])", r"\2", string)
#            ^     ^      ^           ^
#            |     |      |           |
#            |     |      |           |- \2 is interpreted as a group
#            |     |      |              reference
#            |     |      |              
#            |     |      |
#            |     |      -- capture non-greedily until the
#            |     |         end of the punctuation (group 2)
#            |     |
#            |     -- non-capturing group for the [: ] punctuation
#            -- capture a word (group 1)

'he showed his teeth to the dentist'

Could possibly be simplified :)

  • Related