Create a regex from a space-separated list of literal `choices`.

    If provided, `prefix` and `suffix` will be attached to each choice
    individually.
322977
def literals(choices, prefix="", suffix=""):
    
    return "|".join(prefix + re.escape(c) + suffix for c in choices.split())
173905
def parse_regex(regex_tokens):
    
    # We add a closing brace because that represents the final pop of the stack.
    tokens = [')'] + regex_tokens[::-1]

    def wrap(lst):
        """ Turn list into sequence when it contains several items. """
        if len(lst) == 1:
            return lst[0]
        else:
            return Sequence(lst)

    def _parse():
        or_list = []
        result = []

        def wrapped_result():
            if or_list == []:
                return wrap(result)
            else:
                or_list.append(result)
                return Any([wrap(i) for i in or_list])

        while tokens:
            t = tokens.pop()

            if t.startswith('(?P<'):
                variable = Variable(_parse(), varname=t[4:-1])
                result.append(variable)

            elif t in ('*', '*?'):
                greedy = (t == '*')
                result[-1] = Repeat(result[-1], greedy=greedy)

            elif t in ('+', '+?'):
                greedy = (t == '+')
                result[-1] = Repeat(result[-1], min_repeat=1, greedy=greedy)

            elif t in ('?', '??'):
                if result == []:
                    raise Exception('Nothing to repeat.' + repr(tokens))
                else:
                    greedy = (t == '?')
                    result[-1] = Repeat(result[-1], min_repeat=0, max_repeat=1, greedy=greedy)

            elif t == '|':
                or_list.append(result)
                result = []

            elif t in ('(', '(?:'):
                result.append(_parse())

            elif t == '(?!':
                result.append(Lookahead(_parse(), negative=True))

            elif t == '(?=':
                result.append(Lookahead(_parse(), negative=False))

            elif t == ')':
                return wrapped_result()

            elif t.startswith('#'):
                pass

            elif t.startswith('{'):
                # TODO: implement!
                raise Exception('{}-style repitition not yet supported' % t)

            elif t.startswith('(?'):
                raise Exception('%r not supported' % t)

            elif t.isspace():
                pass
            else:
                result.append(Regex(t))

        raise Exception("Expecting ')' token")

    result = _parse()

    if len(tokens) != 0:
        raise Exception("Unmatched parantheses.")
    else:
        return result
1137999
function createRegExpForIgnorePatterns(normalizedOptions) {
    Object.keys(normalizedOptions).forEach(key => {
        const ignorePatternStr = normalizedOptions[key].ignorePattern;

        if (ignorePatternStr) {
            const regExp = RegExp(`^\\s*(?:${ignorePatternStr})`, "u");

            normalizedOptions[key].ignorePatternRegExp = regExp;
        }
    });
}
298985
def str_matcher(mode):
    

    def f_raw(inp_str, pos):
        return unique_literal_cache_pool[mode] if inp_str.startswith(mode, pos) else None

    def f_collection(inp_str, pos):
        for each in mode:
            if inp_str.startswith(each, pos):
                return unique_literal_cache_pool[each]
        return None

    if isinstance(mode, str):
        return f_raw

    if len(mode) is 1:
        mode = mode[0]
        return f_raw

    return f_collection
352703
def _get_parts_of_format_string(resolved_string, literal_texts, format_specs):
    
    _text = resolved_string
    bits = []

    if literal_texts[-1] != '' and _text.endswith(literal_texts[-1]):
        _text = _text[:-len(literal_texts[-1])]
        literal_texts = literal_texts[:-1]
        format_specs = format_specs[:-1]

    for i, literal_text in enumerate(literal_texts):
        if literal_text != '':
            if literal_text not in _text:
                raise ValueError(("Resolved string must match pattern. "
                                  "'{}' not found.".format(literal_text)))
            bit, _text = _text.split(literal_text, 1)
            if bit:
                bits.append(bit)
        elif i == 0:
            continue
        else:
            try:
                format_spec = _validate_format_spec(format_specs[i-1])
                bits.append(_text[0:format_spec])
                _text = _text[format_spec:]
            except:
                if i == len(format_specs) - 1:
                    format_spec = _validate_format_spec(format_specs[i])
                    bits.append(_text[:-format_spec])
                    bits.append(_text[-format_spec:])
                    _text = []
                else:
                    _validate_format_spec(format_specs[i-1])
    if _text:
        bits.append(_text)
    if len(bits) > len([fs for fs in format_specs if fs is not None]):
        bits = bits[1:]
    return bits
451598
public static MessageFormat pluralizeFormat(final String pattern, final String... choices)
    {
        double[] indexes = new double[choices.length];

        for (int i = 0; i < choices.length; i++)
        {
            indexes[i] = i;
        }

        ChoiceFormat choiceForm = new ChoiceFormat(indexes, choices);
        MessageFormat format = (MessageFormat) messageFormat(pattern).clone();
        format.setFormat(0, choiceForm);

        return format;
    }
375832
def trim_common_prefixes(strs, min_len=0):
    """"""

    trimmed = 0

    if len(strs) > 1:
        s1 = min(strs)
        s2 = max(strs)

        for i in range(len(s1) - min_len):
            if s1[i] != s2[i]:
                break
            trimmed = i + 1

    if trimmed > 0:
        strs = [s[trimmed:] for s in strs]

    return trimmed, strs
216382
function concatRegexes (regexes) {
  var rconcat = ''

  if (Array.isArray(regexes)) {
    for (var i = 0, l = regexes.length; i < l; i++) {
      rconcat += regexes[i].source + '|'
    }

    rconcat = rconcat.substr(0, rconcat.length - 1)

    return new RegExp(rconcat)
  }
}
31527
def expand_syntax(string):
    """"""
    match = syntax_pattern.search(string)
    if match:
        prefix = string[:match.start()]
        suffix = string[match.end():]
        intervals = match.group(1).split(',')
        for interval in intervals:
            interval_match = interval_pattern.match(interval)
            if interval_match:
                start = interval_match.group(1)
                end = (interval_match.group(2) or start).strip('-')
                for i in _iter_numbers(start, end):
                    for expanded in expand_syntax(prefix + i + suffix):
                        yield expanded
    else:
        yield string
484669
function regexpToRegexp(regex, keys, options) {
  if (!Array.isArray(keys)) return regex.source;

  let groups = regex.source.match(/\((?!\?)/g);
  if (!groups) return regex.source;

  let i = 0;
  let group = () => ({
    name: i++,
    prefix: null,
    delimiter: null,
    optional: false,
    repeat: false,
    partial: false,
    pattern: null
  });

  groups.forEach(() => keys.push(group()));
  return regex.source;
}
1240575
def from_string(cls, string):
        
        items = shlex.split(string, **cls.split_args)
        return cls(items)
1152691
function getRegExpTags(opt, fileUrl) {
	function parseTag(tag, replacement) {
		return new RegExp(escapeStringRegexp(tag).replace(PATH_REGEX, replacement || FILE_PATH_REGEX), 'g');
	}

	if (fileUrl) {
		return {
			start: parseTag(opt.start, fileUrl),
			end: parseTag(opt.end, fileUrl)
		}
	}
	return {
		start: parseTag(opt.start),
		startex: parseTag(opt.start, "(.+)"),
		end: parseTag(opt.end)
	}
}
424112
def complete_opt_format(self, text, *_):
        
        return [t + " " for t in FORMATTERS if t.startswith(text)]
926321
def _process_regex(cls, regex, rflags, state):
        """"""
        if isinstance(regex, Future):
            regex = regex.get()
        return re.compile(regex, rflags).match
192692
def extract_prefix(self, prefix):
        

        field = re.match(PREFIX_REG, prefix if prefix else '')
        
        return (prefix,) if not field else field.group(1, 2, 3)
167694
def build_regex(self, tokens):
        """"""
        patterns = []
        for token in tokens:
            patterns.append(token.pattern_start)
            if token.pattern_end:
                patterns.append(token.pattern_end)
        return re.compile('|'.join(patterns), re.DOTALL)
1073627
def _setup_regex(self):
        """"""
        self.RE_COMMENTS = cache.RE_COMMENTS
        self.RE_MODULE = cache.RE_MODULE
        self.RE_TYPE = cache.RE_TYPE
        self.RE_EXEC = cache.RE_EXEC
        self.RE_MEMBERS = cache.RE_MEMBERS
        self.RE_DEPEND = cache.RE_DEPEND