
Regex escaper
By:
waterapple on
Dec 19th, 2013 | syntax:
Python | size: 2.25 KB | hits: 44 | expires: Never
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: new
#
# Created: 19/12/2013
# Copyright: (c) new 2013
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
def escape_for_c_sharp(raw_string):
converted_string = ""
for character in raw_string:
# Escape special characters
if character == "\\":
converted_string += "\\\\"# \\
# (
elif character == "(":
converted_string += "\\("# \(
# )
elif character == ")":
converted_string += "\\)"# \)
# [
elif character == "[":
converted_string += "\\["# \[
# ]
elif character == "]":
converted_string += "\\]"# \]
# {
elif character == "{":
converted_string += "\\{"# \{
# }
elif character == "}":
converted_string += "\\}"# \}
# .
elif character == ".":
converted_string += "\\."# \.
# +
elif character == "+":
converted_string += "\\+"# \+
# ^
elif character == "^":
converted_string += "\\^"# \^
# $
elif character == "$":
converted_string += "\\$"# \$
# |
elif character == "|":
converted_string += "\\|"# \|
# *
elif character == "*":
converted_string += "\\*"# \*
# ?
elif character == "?":
converted_string += "\\?"# \?
# Not a special character
else:
converted_string += character
return converted_string
def read_file(path):
"""grab the contents of a file"""
f = open(path, "r")
data = f.read()
f.close()
return data
def save_file(file_name,data):
file = open(file_name, "wb")
file.write(data)
file.close()
def main():
text_to_convert = read_file("input.txt")
converted_text = escape_for_c_sharp(text_to_convert)
save_file("output.txt", converted_text)
print converted_text
if __name__ == '__main__':
main()