Python swap words using regex

Today I learn a lot at Regex, but I'm already stuck. I am trying to swap words using regex in python, but I can't figure it out.

Example

s = 'How are you guys today'
# This is what I tried so far, but i obviously miss something 
# because this is giving an IndexError: no such group
re.sub(r'\w+\w+', r'\2\1', s)

Expected Result

'are How guys you today'
+4
source share
2 answers

You need to use capture groups and match characters without words between words:

import re
s = 'How are you guys today'
print(re.sub(r'(\w+)(\W+)(\w+)', r'\3\2\1', s))
# => are How guys you today

See a Python demo

The sample (\w+)(\W+)(\w+)will fit and capture 3 groups:

  • (\w+)- group 1 (link to a \1 numbered trackback from a replacement template): one or more character words
  • (\w+) - 2 ( \2):
  • (\w+) - 3 ( \3):
+3

. . .

s = 'How are you guys today'
re.sub(r'(\w+ )(\w+ )', r'\2\1', s)
0

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


All Articles