-1

I want to use regex for replacing "," with ", "(comma followed by space) but not at the end of the string:

"a,b,c,d," to "a, b, c, d,"

but also

"Berlin,London,Offenbach,Gera," to "Berlin, London, Offenbach, Gera,"

or

"123,2345,653,12," to "123, 2345, 653, 12,"

I tried in Python

import re

re.sub(r'([1-9a-zA-Z]),([1-9a-zA-Z])', r'\1, \2', "a,b,c,d,")

but get the result:

'a, b,c, d,' (space after comma between "b" and "c" is missing)

What's wrong?

Klem
  • 49
  • 1
  • 8

2 Answers2

1

You may simply replace on ,(?=.), which will only match commas not occurring at the end of the input.

inp = "a,b,c,d,"
output = re.sub(r',(?=.)', ', ', inp)
print(output)  # a, b, c, d,
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

You can use ,(?!$) to match any comma except in the end of line.

import re

print(re.sub(r',(?!$)', r', ', "a,b,c,d,")+'|')
a, b, c, d,|

(| to see lack of trailing space)

Explanation:

  • (?! ... ) is a negative lookahead. It checks that previous match is not followed by content of this group.
  • $ - meta symbol meaning end of string.
markalex
  • 8,623
  • 2
  • 7
  • 32