Created
May 11, 2017 05:42
-
-
Save dansondergaard/5bbab789cbcdf3cc403656664e57fa8c to your computer and use it in GitHub Desktop.
Bash-like string expansion in Python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """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