Skip to content

split

Quote-aware string splitting utilities.

This module provides functions for splitting strings while respecting quoted sections and escaped characters. It supports custom quote maps, nesting rules, and unescaping, making it suitable for parsing shell-like or configuration syntax.

Classes:

Name Description
_Skipper

Tracks quote positions during forward scanning.

SplitContext

Named tuple holding quote mapping and regex patterns.

Main APIs

_chars_regex, _specials_regex, _split_forward, make_context, _to_bytes, split, unquote

make_context(quote_map)

Creates a SplitContext from a quote mapping dictionary.

Parameters:

Name Type Description Default
quote_map

A dict mapping opening quote characters to closing characters.

required

Returns:

Type Description

A SplitContext namedtuple with compiled regex patterns for quote

detection.

Source code in py_misc_utils/split.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def make_context(quote_map):
  """Creates a SplitContext from a quote mapping dictionary.

  Args:
    quote_map: A dict mapping opening quote characters to closing characters.

  Returns:
    A ``SplitContext`` namedtuple with compiled regex patterns for quote
    detection.
  """
  bmap = {ord(k): ord(v) for k, v in quote_map.items()}

  return SplitContext(map=bmap,
                      quote_rx=_chars_regex(bmap.keys()),
                      quote_sprx=_specials_regex(bmap))

split(data, split_rx, quote_ctx=None, unescape=False)

Splits data while respecting quoted sections and escaped characters.

Parameters:

Name Type Description Default
data

A string or bytes object to split.

required
split_rx

A string or compiled regex pattern for the split delimiter.

required
quote_ctx

An optional SplitContext defining quote characters. Defaults to a context with common quote pairs ("'", "'", "`", "()", "{}", "[]", "<>").

None
unescape

If True, backslash-escaped characters are unescaped during splitting.

False

Returns:

Type Description

A tuple of parts (strings if input was str, bytes if input was bytes).

Raises:

Type Description
RuntimeError

If quotes are unmatched at the end of the data.

Example
from py_misc_utils import split as sp

print(sp.split('a, "b, c", d', ','))  # ('a', ' "b, c"', ' d')

# An escaped separator is honored only with unescape=True:
esc_sep = ',' + chr(92) + ','
print(sp.split('x' + esc_sep + 'y', ',', unescape=True))  # ('x,y',)
print(sp.split('x' + esc_sep + 'y', ','))  # ('x\,y',)

# A custom quote context, e.g. only parentheses are special:
ctx = sp.make_context({'(': ')'})
print(sp.split('a, (b, c)', ',', quote_ctx=ctx))  # ('a', ' (b, c)')
Source code in py_misc_utils/split.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
def split(data, split_rx, quote_ctx=None, unescape=False):
  """Splits data while respecting quoted sections and escaped characters.

  Args:
    data: A string or bytes object to split.
    split_rx: A string or compiled regex pattern for the split delimiter.
    quote_ctx: An optional SplitContext defining quote characters. Defaults
      to a context with common quote pairs (\"'\", \"'\", \"`\", \"()\", \"{}\",
      \"[]\", \"<>\").
    unescape: If True, backslash-escaped characters are unescaped during
      splitting.

  Returns:
    A tuple of parts (strings if input was str, bytes if input was bytes).

  Raises:
    RuntimeError: If quotes are unmatched at the end of the data.

  Example:
    from py_misc_utils import split as sp

    print(sp.split('a, "b, c", d', ','))  # ('a', ' "b, c"', ' d')

    # An escaped separator is honored only with unescape=True:
    esc_sep = ',' + chr(92) + ','
    print(sp.split('x' + esc_sep + 'y', ',', unescape=True))  # ('x,y',)
    print(sp.split('x' + esc_sep + 'y', ','))  # ('x\\,y',)

    # A custom quote context, e.g. only parentheses are special:
    ctx = sp.make_context({'(': ')'})
    print(sp.split('a, (b, c)', ',', quote_ctx=ctx))  # ('a', ' (b, c)')
  """
  qctx = quote_ctx or _QUOTE_CTX

  bdata, bsplit_rx = _to_bytes(data, split_rx)
  skipper = _Skipper(qctx.quote_rx)

  sval = ord('\\')
  pos, qstack, parts, seq = 0, [], [], bytearray()
  while pos < len(bdata):
    if seq and seq[-1] == sval:
      if unescape:
        seq[-1] = bdata[pos]
      else:
        seq.append(bdata[pos])

      pos += 1
    elif qstack:
      m = re.search(qctx.quote_sprx, bdata[pos:])
      if not m:
        break

      seq.extend(bdata[pos:pos + m.start()])
      pos += m.start()
      c = bdata[pos]
      tq = qstack[-1]
      if c == tq.closec:
        qstack.pop()
      elif tq.nest_ok and (cc := qctx.map.get(c)) is not None:
        qstack.append(_Quote(cc, pos, c != cc))
      seq.append(c)
      pos += 1
    else:
      kpos, is_split = _split_forward(bdata, pos, bsplit_rx, skipper, seq)
      if is_split:
        parts.append(seq)
        seq = bytearray()
      elif kpos < len(bdata):
        c = bdata[kpos]
        if (cc := qctx.map.get(c)) is not None:
          qstack.append(_Quote(cc, kpos, c != cc))
        seq.append(c)
        kpos += 1
      pos = max(kpos, pos + 1)

  tas.check_eq(len(qstack),
               0,
               msg=f'Unmatched quotes during split: "{data}"\n  {qstack}')
  if seq or parts:
    parts.append(seq)

  return tuple(p.decode() for p in parts) if isinstance(data, str) else tuple(parts)

unquote(data, quote_map=None)

Removes matching quotes from the beginning and end of a string.

If the string starts and ends with a matching quote pair, the quotes are removed and any escaped occurrences of the closing quote are unescaped.

Parameters:

Name Type Description Default
data

The string to unquote.

required
quote_map

An optional dict mapping opening quotes to closing quotes. Defaults to the module-level _QUOTE_MAP.

None

Returns:

Type Description

The string with surrounding quotes removed, or the original string if no

matching quote pair is found.

Example
from py_misc_utils import split as sp

print(sp.unquote('"quoted"'))  # quoted
print(sp.unquote('[lst]'))  # lst
print(sp.unquote('plain'))  # plain
Source code in py_misc_utils/split.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
def unquote(data, quote_map=None):
  """Removes matching quotes from the beginning and end of a string.

  If the string starts and ends with a matching quote pair, the quotes are
  removed and any escaped occurrences of the closing quote are unescaped.

  Args:
    data: The string to unquote.
    quote_map: An optional dict mapping opening quotes to closing quotes.
      Defaults to the module-level ``_QUOTE_MAP``.

  Returns:
    The string with surrounding quotes removed, or the original string if no
    matching quote pair is found.

  Example:
    from py_misc_utils import split as sp

    print(sp.unquote('"quoted"'))  # quoted
    print(sp.unquote('[lst]'))  # lst
    print(sp.unquote('plain'))  # plain
  """
  if len(data) >= 2:
    quote_map = quote_map or _QUOTE_MAP
    cc = quote_map.get(data[0])
    if cc == data[-1]:
      udata = data[1:-1]

      return re.sub(rf'\\{cc}', rf'{cc}', udata) if cc == data[0] else udata

  return data