Return the span of the first group that matches the pattern.
776641
def _get_span(s, pattern):
    """"""
    i, j = -1, -1

    match = pattern.match(s)
    if not match:
        return i, j

    for group_name in pattern.groupindex:
        i, j = match.span(group_name)
        if (i, j) != (-1, -1):
            return i, j

    return i, j
872254
public static List<String> regexGroups(Pattern regex, String str) {
    if (str == null) {
      return null;
    }

    Matcher matcher = regex.matcher(str);
    if (!matcher.find()) {
      return null;
    }

    List<String> groups = new ArrayList<String>();
    for (int index = 1; index <= matcher.groupCount(); index++) {
      groups.add(matcher.group(index));
    }

    return groups;
  }
486373
def _find_groups(self) -> Tuple[Optional[str], Optional[int]]:
        
        pattern = self.regex.pattern
        if pattern.startswith("^"):
            pattern = pattern[1:]
        if pattern.endswith("$"):
            pattern = pattern[:-1]

        if self.regex.groups != pattern.count("("):
            # The pattern is too complicated for our simplistic matching,
            # so we can't support reversing it.
            return None, None

        pieces = []
        for fragment in pattern.split("("):
            if ")" in fragment:
                paren_loc = fragment.index(")")
                if paren_loc >= 0:
                    pieces.append("%s" + fragment[paren_loc + 1 :])
            else:
                try:
                    unescaped_fragment = re_unescape(fragment)
                except ValueError:
                    # If we can't unescape part of it, we can't
                    # reverse this url.
                    return (None, None)
                pieces.append(unescaped_fragment)

        return "".join(pieces), self.regex.groups
1296650
def match_pagination(ref_line):
    """"""
    pattern = ur'\(?\[?(\d{1,4})\]?\)?\.?\s*$'
    re_footer = re.compile(pattern, re.UNICODE)
    match = re_footer.match(ref_line)
    if match:
        return int(match.group(1))
    return None
584790
public static String regex_group(EvaluationContext ctx, Object text, Object pattern, Object groupNum) {
        String _text = Conversions.toString(text, ctx);
        String _pattern = Conversions.toString(pattern, ctx);
        int _groupNum = Conversions.toInteger(groupNum, ctx);

        try {
            // check whether we match
            int flags = Pattern.CASE_INSENSITIVE | Pattern.MULTILINE;
            Pattern regex = Pattern.compile(_pattern, flags);
            Matcher matcher = regex.matcher(_text);

            if (matcher.find()) {
                if (_groupNum < 0 || _groupNum > matcher.groupCount()) {
                    throw new RuntimeException("No such matching group " + _groupNum);
                }

                return matcher.group(_groupNum);
            }
        } catch (PatternSyntaxException ignored) {}

        return "";
    }
1060834
def get_match_number(self, pattern, case=False, regexp=False):
        """"""
        position = self.textCursor().position()
        source_text = self.get_text(position_from='sof', position_to=position)
        match_number = self.get_number_matches(pattern,
                                               source_text=source_text,
                                               case=case, regexp=regexp)
        return match_number
274718
private int getMatchingPoint(String pattern, String itemName) {
        int index = pattern.indexOf('*');
        if (index == -1) {
            return -1;
        }

        String firstPart = pattern.substring(0, index);
        int indexFirstPart = itemName.indexOf(firstPart, 0);
        if (indexFirstPart == -1) {
            return -1;
        }

        String secondPart = pattern.substring(index + 1);
        int indexSecondPart = itemName.indexOf(secondPart, index + 1);
        if (indexSecondPart == -1) {
            return -1;
        }

        return firstPart.length() + secondPart.length();
    }
1254100
def get_matched_token(self, match):
        """"""
        match_groupdict = match.groupdict()
        for group in self.groups:
            if match_groupdict[group] is not None:
                token, match_type = self.groups[group]
                return (token, match_type, group)
355396
def _fullmatch(pattern, text, *args, **kwargs):
    """"""
    match = re.match(pattern, text, *args, **kwargs)
    return match if match.group(0) == text else None
345876
def find_multiline_pattern(self, regexp, cursor, findflag):
        """"""
        pattern = to_text_string(regexp.pattern())
        text = to_text_string(self.toPlainText())
        try:
            regobj = re.compile(pattern)
        except sre_constants.error:
            return
        if findflag & QTextDocument.FindBackward:
            # Find backward
            offset = min([cursor.selectionEnd(), cursor.selectionStart()])
            text = text[:offset]
            matches = [_m for _m in regobj.finditer(text, 0, offset)]
            if matches:
                match = matches[-1]
            else:
                return
        else:
            # Find forward
            offset = max([cursor.selectionEnd(), cursor.selectionStart()])
            match = regobj.search(text, offset)
        if match:
            pos1, pos2 = match.span()
            fcursor = self.textCursor()
            fcursor.setPosition(pos1)
            fcursor.setPosition(pos2, QTextCursor.KeepAnchor)
            return fcursor
437227
def parse_pattern_list(liststr):
    """"""
    _re_patt = re.compile("^(.*)=(.*)")
    patterns = []
    for ss in liststr.split(';'):
        match = _re_patt.match(ss)
        if match:
            desc = match.group(1)
            patt = match.group(2).split(',')
            patterns.append((desc, patt))
    return patterns
137212
def span_case(self, i, case):
        """"""

        # A new \L, \C or \E should pop the last in the stack.
        if self.span_stack:
            self.span_stack.pop()
        if self.single_stack:
            self.single_stack.pop()
        self.span_stack.append(case)
        count = len(self.span_stack)
        self.end_found = False
        try:
            while not self.end_found:
                t = next(i)
                if self.use_format and t in _CURLY_BRACKETS:
                    self.handle_format(t, i)
                elif t == '\\':
                    try:
                        t = next(i)
                        self.reference(t, i)
                    except StopIteration:
                        self.result.append(t)
                        raise
                else:
                    self.result.append(self.convert_case(t, case))
                if self.end_found or count > len(self.span_stack):
                    self.end_found = False
                    break
        except StopIteration:
            pass
        if count == len(self.span_stack):
            self.span_stack.pop()
511439
def get_number_matches(self, pattern, source_text='', case=False,
                           regexp=False):
        """"""
        pattern = to_text_string(pattern)
        if not pattern:
            return 0

        if not regexp:
            pattern = re.escape(pattern)

        if not source_text:
            source_text = to_text_string(self.toPlainText())

        try:
            if case:
                regobj = re.compile(pattern)
            else:
                regobj = re.compile(pattern, re.IGNORECASE)
        except sre_constants.error:
            return None

        number_matches = 0
        for match in regobj.finditer(source_text):
            number_matches += 1

        return number_matches
724487
def regex_parse_template(self, template, pattern):
        

        groups = []
        literals = []
        replacements = _compile_replacement_helper(pattern, template)
        count = 0
        for part in replacements:
            if isinstance(part, int):
                literals.append(None)
                groups.append((count, part))
            else:
                literals.append(part)
            count += 1
        return groups, literals
849632
def _pattern_match(self, item, pattern):
        """"""
        if pattern.endswith('*'):
            return item.startswith(pattern[:-1])
        else:
            return item == pattern
1335608
def group_re(self):
        '''  '''
        out = ''
        for token, data in self.tokens():
            if   token == 'TXT':  out += re.escape(data)
            elif token == 'VAR':  out += '(?P<%s>%s)' % (data[1], data[0])
            elif token == 'ANON': out += '(?:%s)' % data
        return out
1284314
def get_block_start(lines, lineno, maximum_indents=80):
    """"""
    pattern = get_block_start_patterns()
    for i in range(lineno, 0, -1):
        match = pattern.search(lines.get_line(i))
        if match is not None and \
           count_line_indents(lines.get_line(i)) <= maximum_indents:
            striped = match.string.lstrip()
            # Maybe we're in a list comprehension or generator expression
            if i > 1 and striped.startswith('if') or striped.startswith('for'):
                bracs = 0
                for j in range(i, min(i + 5, lines.length() + 1)):
                    for c in lines.get_line(j):
                        if c == '#':
                            break
                        if c in '[(':
                            bracs += 1
                        if c in ')]':
                            bracs -= 1
                            if bracs < 0:
                                break
                    if bracs < 0:
                        break
                if bracs < 0:
                    continue
            return i
    return 1