Access substring substrings when using regular expressions in Python

I want to combine two regular expressions A and B, where A and B are displayed as "AB". Then I want to insert a space between A and B so that it becomes "AB".

For example, if A = [0-9] and B =! +, I want to do something like the following.

match = re.sub('[0-9]!+', '[0-9] !+', input_string) 

But this clearly does not work, as it will replace any matches with the string '[0-9]! + '.

How to do it in regular expressions (preferably on one line)? Or does it take a few tedious steps?

+4
source share
1 answer

Use groups!

 match = re.sub('([0-9])(!+)', r'\1 \2', input_string); 

\1 and \2 indicate the first and second brackets. The r prefix is ​​used to store the \ character.

+8
source

Source: https://habr.com/ru/post/1392244/


All Articles