2

Trying to understand Python re.replace I was trying to switch groups by index or by name but encountered a problem using re to do that.

let's say: line = '23 24" #and I want to get '242 231'

nline = re.sub(r"(\d+) (\d+)", r"\2 \1", line)
#This will result '24 23'

but if I add numbers following the index - I will get invalid index: nline = re.sub(r"(\d+) (\d+)", r"\22 \11", line)

I have tried to use name group - but failed to make it work: nline = re.sub(r"(?P\d+) (?P\d+)", r"\s2 \f1", line)

line = '23 24"
#Trial#1
nline = re.sub(r"(\d+) (\d+)", r"\22 \11", line)
#Trial #2
nline = re.sub(r"(?P<f>\d+) (?P<s>\d+)", r"\s2 \f1", line)

I would like to know how to replace a group index followed by another number

and how to use group name in the back reference

Moshe Raz
  • 33
  • 1
  • 3
  • I have asked regarding both index and name. The missing part was for using (?P) which then can be backreferenced using /g. Thanks – Moshe Raz May 19 '19 at 07:29

1 Answers1

3

Try this alternative syntax:

re.sub(r"(\d+) (\d+)", r"\g<2>2 \g<1>1", "23 24")

More here: https://docs.python.org/3.7/library/re.html#re.sub

olinox14
  • 5,087
  • 1
  • 14
  • 34