Reputation: 1769
I am learning a lot of Regex today, but I'm already stuck at something. I am trying to swap words using regex in python, but I can't seem to figure this 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'
Upvotes: 4
Views: 3078
Reputation: 626738
You need to use capturing groups and match non-word chars in 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 the Python demo
The (\w+)(\W+)(\w+)
pattern will match and capture 3 groups:
(\w+)
- Group 1 (referred to with \1
numbered backreference from the replacement pattern): one or more word chars(\W+)
- Group 2 (referred to with \2
): one or more non-word chars(\w+)
- Group 3 (referred to with \3
): one or more word charsUpvotes: 9
Reputation: 2198
You need to use groups to achieve this. You should also indicate spaces in your groups. The following outputs what you want.
s = 'How are you guys today'
re.sub(r'(\w+ )(\w+ )', r'\2\1', s)
Upvotes: 1