Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python swap words using regex

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'
like image 592
Ludisposed Avatar asked Mar 10 '23 04:03

Ludisposed


2 Answers

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 chars
like image 138
Wiktor Stribiżew Avatar answered Mar 29 '23 23:03

Wiktor Stribiżew


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)
like image 41
mohammad Avatar answered Mar 29 '23 23:03

mohammad