2

I am trying to write a regex for python that replaces a dot, space or newline (and any combination of these) with a single comma. I don't understand why my regex is not working.

    newline = line.replace("[\. \\n]+",",")
Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133
Divi
  • 1,614
  • 13
  • 23

2 Answers2

2

You need to use sub to be able to use regex in search replace.

# your code goes here
import re
line = "something with space . dot";
line = re.sub(r'[. \n]+', ",", line);
print line;

Demo

Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133
0

The characters in between the square brackets ("character class") are literals so don't need escaping. Try [. \n]+ instead.

Edit

According to this answer Python string.replace regular expression replace does not recognise regex and you need to use sub

Community
  • 1
  • 1
garyh
  • 2,782
  • 1
  • 26
  • 28
  • It did not work. Normally I can get it work in R. Not sure if python is any issue here. – Divi May 23 '14 at 10:02
  • Could be. I'm not well up on Python. Have a look at http://stackoverflow.com/q/3997525/1425848 – garyh May 23 '14 at 10:04
  • According to this answer http://stackoverflow.com/q/16720541/1425848 `replace` does not recognise regex and you need to use `sub` – garyh May 23 '14 at 10:06