Skip to content

Instantly share code, notes, and snippets.

@dansondergaard
Created May 11, 2017 05:42
Show Gist options
  • Select an option

  • Save dansondergaard/5bbab789cbcdf3cc403656664e57fa8c to your computer and use it in GitHub Desktop.

Select an option

Save dansondergaard/5bbab789cbcdf3cc403656664e57fa8c to your computer and use it in GitHub Desktop.
Bash-like string expansion in Python.
"""Bash-like string expansion in Python.
Author: Dan Søndergaard <[email protected]>
License: MIT
"""
import re
from itertools import product
GROUP_RE = re.compile(r'\{.+?\}')
def _parse_group(s, match):
group_str = s[match.start() + 1:match.end() - 1]
return group_str.split(',')
def iterexpand(s):
fmt = re.sub(GROUP_RE, r'{}', s)
groups = (_parse_group(s, match) for match in re.finditer(GROUP_RE, s))
return (fmt.format(*reps) for reps in product(*groups))
def expand(s):
return list(iterexpand(s))
print(expand('a.{c,d}'))
# => ['a.c', 'a.d']
print(expand('{a,b}.{c,d}'))
# => ['a.c', 'a.d', 'b.c', 'b.d']
print(expand('{a,b,c}/{d,e}.{f,g}'))
# => ['a/d.f', 'a/d.g', 'a/e.f', 'a/e.g', 'b/d.f', 'b/d.g', 'b/e.f', 'b/e.g', 'c/d.f', 'c/d.g', 'c/e.f', 'c/e.g']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment