0

I am trying to replace a string in a file using python re lib. But I failed on replacing some texts with some special characters, like, (), ?, etc. Can anyone help me look at this issue?

I attached my code in here.:

filterText = '\"' + sheet.row_values(row)[1] + '\"';
print "filterText = %s"%filterText;
pattern = re.compile(filterText, re.S);
replacedText = '\"' + sheet.row_values(row)[2] + '\"';
print "replacedText = %s"%replacedText;

if filterText == "English (UK)":
    print "replacedText = %s"%replacedText;

fileContent = re.sub(pattern, replacedText, fileContent);
Bowdzone
  • 3,827
  • 11
  • 39
  • 52
ping
  • 33
  • 5
  • 2
    Is this supposed to be Python? Then why all the semicolons? – Daniel Roseman Nov 02 '15 at 07:33
  • 1
    And you'll need to show examples of the contents. Are you sure you need regexes here? – Daniel Roseman Nov 02 '15 at 07:33
  • Thanks for your quick response. Acturally, I am trying to convert a file with English words to another language. I got an excel from customer which contains English text and Vietnamese together. – ping Nov 02 '15 at 07:39

1 Answers1

1

re.escape(string)

Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

Use re.escape to convert any string as a literal pattern.

filterText = '\"' + re.escape(sheet.row_values(row)[1]) + '\"'
Mariano
  • 6,423
  • 4
  • 31
  • 47