When you use `|` with a group in Python re.sub() regular expression, you want to use a matching string in the string to be replaced.

Asked 1 months ago, Updated 1 months ago, 2 views

What should I do if I want to use the matching string in re.sub() as the replacement string?

I follow the method described in the document, but it does not print well.

Current state code

import re

if__name__=='__main__':
    tmp = re.sub('(a|b)', '\1\n', 'aiueobcd')
    print(tmp)

Expected Output

a
iueob
cd

Actual Output

Output Results

ReferencesSite

re--- Regular Expression Manipulation—Python 3.9.4 Documentation
Python|Replace a string that matches a regular expression with a new string (Pattern.sub, Pattern.subn)

environment

 p python --version     
Python 3.9.5

Thank you for your cooperation.

python regular-expression

2022-09-30 14:18

1 Answers

We recommend using the Raw string in Metropolis's comment, but if you do not want to use the Raw string,

#tmp=re.sub('(a|b)', '\1\n', 'aiueobcd')
tmp = re.sub('(a|b)', '\\1\n', 'aiueobcd')

as


2022-09-30 14:18

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.