0

I'm trying to use regex in python to replace strings. I'd like to replace "SERVERS)" with "SERV" in a string.

example_String = "This is a great SERVERS)"

re.sub("SERVERS)","SERV", example_String)

I expected it to be a straight forward swap, but as I read more into the error, it looks like I need to set the regex pattern to read the ")" as a regular character and not a special regex character.

I'm not very familiar with regex , and would appreciate the help!

Edit : I'm importing data from a database (which is user input), there's quite a few similar issues as mentioned in the question. re.escape() fits the bill perfectly , thanks!

sai
  • 139
  • 1
  • 1
  • 7

1 Answers1

1

You could go for

import re

example_String = "This is a great SERVERS)"
new_string = re.sub(r"SERVERS\)","SERV", example_String)
print(new_string)

Which yields

This is a great SERV


To be honest, no regular expression is needed, really:
example_String = "This is a great SERVERS)"
new_string = example_String.replace('SERVERS)', 'SERV')
print(new_string)

In the latter, you don't even need to escape anything and it will be faster.

Jan
  • 42,290
  • 8
  • 54
  • 79
  • 2
    If it's a user's input of `SERVERS)` you can also use python's [`re.escape()`](https://stackoverflow.com/questions/280435/escaping-regex-string-in-python) method – ctwheels Dec 04 '17 at 19:25