简体   繁体   中英

Number of matches in regex substitution

I am looking for a Pythonic way to simplify this code:

fix = re.compile(r'((?<=>\n)(\t){2}(?=<))')
fixed_output = re.sub(fix, 1*2*' ', fixed_output)
fix = re.compile(r'((?<=>\n)(\t){3}(?=<))')
fixed_output = re.sub(fix, 2*2*' ', fixed_output)
# and so on...

That is: if there are n tab characters between ">" and "<", they are replaced by *(n-1) * 2* characters. Can this be generalized to a single regular expression? In other words, is it possible to write a regular expression that uses the number of matches in order to determine the replacement string?

You can use a function instead of a fixed replacement string and take the number of matched tabulator characters to generate the replacement, for example:

re.sub(r'((?<=>\n)\t{2,}(?=<))', lambda m: (len(m.group(0))-1)*2*" ", string)

Here the lambda expression lambda m: (len(m.group(0))-1)*2*" " is used to replace n tabulator character by ( n -1)·2 spaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM