-1

I'm trying to use python to run regex to do the replacement like below:

a = "%I'm a sentence.|"
re.sub(r"%(.*?)\|", "<\1>", a)

Then b = <\1>, but I want to get the result of <I'm a sentences.>

How am I supposed to achieve this? I tried to group I'm a sentence, but I feel I did something wrong, so the result doesn't maintain the group 1. If you have any ideas, please let me know. Thank you very much in advance!

Barmar
  • 741,623
  • 53
  • 500
  • 612
Penny
  • 1,218
  • 1
  • 13
  • 32

2 Answers2

5

Use a raw string for the replacement, otherwise \1 will be interpreted as an octal character code, not a back-reference.

And assign the result to b.

b = re.sub(r"%(.*?)\|", r"<\1>", a)

DEMO

Barmar
  • 741,623
  • 53
  • 500
  • 612
3

to capture group use \g<1>

a = "%I'm a sentence.|"
a = re.sub(r"%(.*?)\|", "<\g<1>>", a)
# <I'm a sentence.>
ewwink
  • 18,382
  • 2
  • 44
  • 54