Python Regex instantly replace groups
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping
--
Chapters
00:00 Question
00:34 Accepted answer (Score 299)
01:07 Answer 2 (Score 72)
01:39 Thank you
--
Full question
https://stackoverflow.com/questions/1400...
Accepted answer links:
[re.sub]: http://docs.python.org/library/re.html#r...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #regex #regexgroup
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping
--
Chapters
00:00 Question
00:34 Accepted answer (Score 299)
01:07 Answer 2 (Score 72)
01:39 Thank you
--
Full question
https://stackoverflow.com/questions/1400...
Accepted answer links:
[re.sub]: http://docs.python.org/library/re.html#r...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #regex #regexgroup
#avk47
ACCEPTED ANSWER
Score 323
Have a look at re.sub:
result = re.sub(r"(\d.*?)\s(\d.*?)", r"\1 \2", string1)
This is Python's regex substitution (replace) function. The replacement string can be filled with so-called backreferences (backslash, group number) which are replaced with what was matched by the groups. Groups are counted the same as by the group(...) function, i.e. starting from 1, from left to right, by opening parentheses.
ANSWER 2
Score 80
The accepted answer is perfect. I would add that group reference is probably better achieved by using this syntax:
r"\g<1> \g<2>"
for the replacement string. This way, you work around syntax limitations where a group may be followed by a digit. Again, this is all present in the doc, nothing new, just sometimes difficult to spot at first sight.