Revision 14538
Added by Aaron Marcuse-Kubitza over 10 years ago
trunk/lib/strings.py | ||
---|---|---|
99 | 99 |
|
100 | 100 |
##### Escaping |
101 | 101 |
|
102 |
def no_esc_prefix_re(esc='\\'): |
|
103 |
esc_re = re.escape(esc) |
|
104 |
return '(?<!'+esc_re+')((?:'+esc_re+'{2})*)' # an even # of escs |
|
105 |
|
|
106 |
def escd_char_re(escd_char, esc): |
|
107 |
assert escd_char != esc # not supported; use str_.replace() instead |
|
108 |
return no_esc_prefix_re(esc)+re.escape(escd_char) |
|
109 |
|
|
110 |
def esc_re_map(map_): |
|
111 |
''' |
|
112 |
for use with replace_all_re() |
|
113 |
@param map_ [(escd_char, char), ...] # use flip_map() if needed |
|
114 |
@return [(escd_char_re, escd_char_re_sub), ...] |
|
115 |
''' |
|
116 |
_1st_escd_char = map_[0][0] # 1st entry > escd_char |
|
117 |
esc = _1st_escd_char[0] # esc char is 1st char |
|
118 |
return [(escd_char_re(escd_char, esc), r'\1'+char) |
|
119 |
for escd_char, char in map_] |
|
120 |
|
|
102 | 121 |
def esc_quotes(str_, quote='"', esc='\\', quote_esc=None): |
103 | 122 |
if quote_esc == None: quote_esc = esc+quote |
104 | 123 |
|
... | ... | |
106 | 125 |
str_ = str_.replace(quote, quote_esc) |
107 | 126 |
return str_ |
108 | 127 |
|
128 |
def unesc_quotes(str_, quote='"', esc='\\', quote_esc=None): |
|
129 |
if quote_esc == None: quote_esc = esc+quote |
|
130 |
|
|
131 |
# can't use `.decode('string_escape')` for this because it doesn't decode |
|
132 |
# custom escapes, such as GWT's \! for | |
|
133 |
return replace_all_re(esc_re_map([(quote_esc, quote)]), |
|
134 |
str_).replace(esc+esc, esc) |
|
135 |
|
|
109 | 136 |
json_encode_map = [ |
110 | 137 |
('\n', r'\n'), |
111 | 138 |
('\r', r'\r'), |
Also available in: Unified diff
lib/strings.py: added unesc_quotes() and helper functions