-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
  • 669,327
  • 51
  • 454
  • 560
Penny
  • 1,150
  • 1
  • 10
  • 31

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
  • 669,327
  • 51
  • 454
  • 560
3

to capture group use \g<1>

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