Switch the order of words using Python regex

338
August 05, 2017, at 11:44 AM

I found this code that switches YYYY-MM-DD to DD-MM-YYYY

b = re.sub(r'(\d{4})-(\d{1,2})-(\d{1,2})', '\\3-\\2-\\1', "2004-05-16")

So I'm trying to convert the string 'hey you man' to 'man hey you' but cannot do it. I was able to group the string with:

b = re.findall(r'(\w+)', 'hey you man')

But when I do the following I get an error:

b = re.sub(r'(\w+)','\\3\\2\\1',"hey you man")

Also, I'm not interested in non-regex solutions. I can switch the strings around using other methods, I'm just interested in learning about regexes.

Answer 1

You need to capture the words you want to switch in three separate groups (in your case, you have only one capture group); Here \1, \2, \3 are back references referring to the captured groups (in parenthesis) in order, i.e. \1 - hey, \2 - you, \3 - man; By reordering these back references in the replacement, the words are reordered in the result:

re.sub(r'(\w+) (\w+) (\w+)', r'\3 \1 \2',"hey you man")
# 'man hey you'
READ ALSO
How to read (stream) files from Google Drive in memory in python?

How to read (stream) files from Google Drive in memory in python?

I'm trying to read large CSV files that are dropped on Google Drive using the google-api-python-client https://googlegithub

448
Mixture model fitting (Bimodal?) in SciPy using truncated normals. Python 3

Mixture model fitting (Bimodal?) in SciPy using truncated normals. Python 3

I'm trying to follow this as an example but can't seem to adapt it to work with my dataset since I need truncated normals: https://stackoverflowcom/questions/35990467/fit-two-gaussians-to-a-histogram-from-one-set-of-data-python#=

448
Differences between CV2 image processing and tf.image processing

Differences between CV2 image processing and tf.image processing

I recently switched out using cv2 for Tensorflow's tfimage module for image processing

428