2 # Copyright 2014 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
8 def quote(input_str
, specials
, escape
='\\'):
9 """Returns a quoted version of |str|, where every character in the
10 iterable |specials| (usually a set or a string) and the escape
11 character |escape| is replaced by the original character preceded by
12 the escape character."""
14 assert len(escape
) == 1
16 # Since escape is used in replacement pattern context, so we need to
17 # ensure that it stays a simple literal and cannot affect the \1
18 # that will follow it.
22 return re
.sub(r
'(' + r
'|'.join(specials
)+r
'|'+escape
+ r
')',
23 escape
+ r
'\1', input_str
)
24 return re
.sub(r
'(' + escape
+ r
')', escape
+ r
'\1', input_str
)
27 def unquote(input_str
, specials
, escape
='\\'):
28 """Splits the input string |input_str| where special characters in
29 the input |specials| are, if not quoted by |escape|, used as
30 delimiters to split the string. The returned value is a list of
31 strings of alternating non-specials and specials used to break the
32 string. The list will always begin with a possibly empty string of
33 non-specials, but may end with either specials or non-specials."""
35 assert len(escape
) == 1
43 lit_next
= (c
== escape
)
44 if c
not in specials
or lit_next
:
46 out
.append(''.join(cur_out
))
58 lit_next
= c
== escape
63 out
.append(''.join(cur_out
))
66 out
.append(''.join(cur_out
))