Home > front end >  match any character followed by exclamation mark and replace it with a whitespace and a exclamation
match any character followed by exclamation mark and replace it with a whitespace and a exclamation

Time:01-05

I have the following sentences:

hello!
hello?
goodbye!!!
goodbye???

I want a regex to modify them like this:

hello !
hello ?
goodbye !!!
goodbye ???

I tried with:

re.sub(r"(\w)\1([!?])\2", r'\1 \2', sentence)

But it didn't work.

CodePudding user response:

Try this:

\b([?!])

\b word boundary.

([?!]) a literal ? or !.

See regex demo

re.sub(r"\b([?!])", r' \1', sentence)
  • Related