2
votes

I have a string with multiple commas and spaces as delimiters between words. Here are some examples:

ex #1: string = 'word1,,,,,,,     word2,,,,,,     word3,,,,,,'  
ex #2: string = 'word1         word2       word3'  
ex #3: string = 'word1,word2,word3,'  

I want to use a regex to convert either of the above 3 examples to "word1, word2, word3" - (Note: no comma after the last word in the result).

I used the following code:

import re
input_col = 'word1    ,   word2     , word3,    '
test_string = ''.join(input_col)
test_string = re.sub(r'[,\s]+', ' ', test_string)
test_string = re.sub(' +', ',', test_string)
print(test_string)  

I get the output as "word1,word2,word3,". Whereas I actually want "word1, word2, word3". No comma after word3.

What kind of regex and re methods should I use to achieve this?

4

4 Answers

3
votes

you can use the split to create an array and filter len < 1 array

import re
s='word1    ,   word2     , word3,    '
r=re.split("[^a-zA-Z\d]+",s)
ans=','.join([ i for i in r if len(i) > 0 ])
0
votes

How about adding the following sentence to the end your program:

re.sub(',+$','', test_string)

which can remove the comma at the end of string

0
votes

One approach is to first split on an appropriate pattern, then join the resulting array by comma:

string = 'word1,,,,,,,     word2,,,,,,     word3,,,,,,'
parts = re.split(",*\s*", string)
sep = ','
output = re.sub(',$', '', sep.join(parts))
print(output

word1,word2,word3

Note that I make a final call to re.sub to remove a possible trailing comma.

0
votes

You can simply use [ ]+ to detect extra spaces and ,\s*$ to detect the last comma. Then you can simply substitute the [ ]+,[ ]+ with , and the last comma with an empty string

import re
input_col = 'word1    ,   word2     , word3,    '
test_string = re.sub('[ ]+,[ ]+', ', ', input_col) # remove extra space
test_string = re.sub(',\s*$', '', test_string) # remove last comma
print(test_string)